get current page not full url - php

Is it possible to save the current page in a variable (not the full url) using php
So if my page is www.mywebsite.com/news/bob
I am looking to get /bob in a variable.

<?PHP $file_name = $_SERVER['PHP_SELF']; ?>

see this variable
$_SERVER['PATH_INFO']
maybe you need
basename($_SERVER['PATH_INFO']);

$_SERVER['PATH_INFO'] doesn't seem to exist on my install. Not sure what the story is there, but if it's not on mine, it may not be on yours so here's some alternatives.
$current_page = '/' . basename($_SERVER['PHP_SELF']);
$current_page = '/' . basename($_SERVER['REQUEST_URI']);
$current_page = '/' . basename($_SERVER['SCRIPT_NAME']);
I find $_SERVER['PHP_SELF'] to be quite dependable.
If you're fond of regular expressions you could try
$current_page = preg_replace('/(.*?\/)+(.*)$/', '/$2', $_SERVER['PHP_SELF']);

If you are using $_SERVER['PHP_SELF'] on included or required files, then it will return the current file, not the URL of the current page. On Windows machines, the only reliable options are $_SERVER['REQUEST_URI'] or $_SERVER['HTTP_X_ORIGINAL_URL'] however, these will include any querystring as well.
You would need to strip the query string off the end of the URL to get the part you want.
$current_page = $_SERVER['REQUEST_URI'];
$current_page = substr($current_page, 0, strpos($current_page, "?")); //removes query string
$current_page = = '/' . array_pop(array_filter(explode("/", $current_page)));

Related

Create simple HTML demos based on template with different URL paths

I would like to obtain on my localhost (somehow dynamically) the following URLs:
localhost/demo1/
localhost/demo2/
localhost/demo3/
...
and so on (more than 30).
I have an index.php file which I would like to use as a template for each of the above paths.
When I access localhost/demoX/ I would like to load the index.php template only with some few changes inside, based on the demoX name.
Can you tell me how to obtain this structure?
Thanks
Use PHP
1) Parse site URL (hint for url "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']) to get variable you need (I think you will use RegEx for that)
2) $template = require_once('index.php');
3) Process all variables used in index.php
4) echo $template; exit();
NOT TESTED PSEUDO CODE
$url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$part = preg_match("/demo(\d+)/", $url)[0];
$partName = "File name is demo-{$part}";
$template = require_once('index.php');
echo $template;
exit();
[index.php]
<?php
echo $partName;

PHP: How to get only the current folder of a website

For example I have a website that points to a page like this:
http://www.mysite.com/folder/file
How can I get determine /folder so that I can go further an quote an if statement like
if /folder then echo something
Why do I need this?
I am trying to tell facebook which image to pick from a page. Actually I have a pretty simple page structure and the image that facebook should take is always at first but somehow it does choose another one from time to time. I guess because the other images are loaded faster. And the old way to rel="img_src" doesn't seem to work anymore as that I could just add it to the wanted image.
So well of course I use the open graph protocol to tell facebook which Image it should use.
I am working with a cms were I can output the path of the image depending on the id the image has. I have two different id's for the different kind of pages living in two different folders.
This leads to:
if index --> echo meta og for index img
else if /folderone (with id1) --> echo meta og for id1
else if /foldertwo (with id2) --> echo meta og for id2
This is why I need to know the foldername.
Now with the answer I have following setup, just that you know:
<?php $folder = dirname($_SERVER['SCRIPT_NAME']); ?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/") echo "<meta property='og:image' content='http://www.mysite.com/img/img.jpg'/>" ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderOne") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id1}'/> " ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderTwo") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id2}'/> " ;?>
parse_url &
explode
$path = parse_url($url, PHP_URL_PATH);
gives you
/folder/file
then you can explode() to separate the path values and check the first one to see if it is 'folder'
Example here: http://tehplayground.com/#7TIKAwp6J
Example code:
$url = "http://www.mysite.com/folder/file";
$path = parse_url($url, PHP_URL_PATH);
$arr = explode("/",$path);
echo $arr[1]; // leading slash makes [0] ""
outputs
folder
$script = $_SERVER['SCRIPT_NAME'];
echo dirname($script);
Possibly use "get current working directory" function getcwd()?
Explode it by directory separator.
Then grab the last element like this:
$var = getcwd();
$var = explode('\\', $var); // your OS might use '/' instead
$var = end($var);
I suppose this assumes you're not using some kind of MVC framework that uses routing.
I hope that helps!
I think this is nicer than exploding the string:
function getCurrentDirectory(){
$curDirPath = getcwd();
return substr($curDirPath, strrpos($curDirPath, '/') + 1);
}
getcwd() gives you the current directory's path, and then you can truncate it starting right after the last occurrence of the / in its file path.
$dir_list = explode('/', dirname($_SERVER['SCRIPT_FILENAME']));
$this_folder = $dir_list[count($dir_list)-1];
...
if ($this_folder) == "folderOne") echo "...."
...
if(dirname('yoursite/folder')){

PHP: redirect after get url

I need "calculate" an URL and redirect to it. I have the following code:
<?php
//Basic HTML parsing with PHP
include("simple_html_dom.php");
$htmlCode = file_get_html('http://example.net/example.html');
foreach($htmlCode->find('div[class=frontPageImage]') as $element) {
foreach($element->find('img') as $imagee)
$imgurl = $imagee->src;
}
header("'Location:".$imgurl."'");
?>
First in $imgurl get the url and later redirect to that url... but it doesn't work..
any idea or suggestion? thanks
header("'Location:".$imgurl."'");
Should probably be:
header("Location: " . $imgurl);
I removed the single quote ' because your HTTP header would look like:
'Location: http://site.com/image.jpg'
which is invalid because of the single quotes.
You are also looping and finding many image URL's but only redirecting to the last one.

How to make PHP header location redirect use PHP generated URL

This is fairly simple but I cant work it out.
I'm building a wordpress site, and I want a redirect on my 404 page using PHP instead of javascript.
<?php header("Location: www.myblogurl.com"); ?>
And I use this in my wordrpess websites to get the URL of my blog...
<?php bloginfo('url'); ?>
But I can't seem to merge the two PHP scripts together, please see my poor attempt below.
<?php
$location = bloginfo('url');
header( 'Location:' + $location ) ;
?>
This seems to echo my website URL instead of redirecting.
Can any help me please, thanks.
bloginfo in wordpress echo's the information instead of returning it. You should use get_bloginfo.
The docs says:
This always prints a result to the browser. If you need the values for use in PHP, use get_bloginfo().
A sample would be:
<?php
header('Location: ' . get_bloginfo('url'));
?>
You are using the + to concatenate 2 strings. This is wrong in PHP the + is a math operator for things like $result = 1 + 1. You need to use the . operator: $text = 'hello' . 'world'.
Well first correct + with .
String concatenation works in php with .
<?php
$location = bloginfo('url');
header( 'Location: ' . $location ) ;
?>
try to use get_bloginfo() instead of bloginfo() and replace the + with .
Use this:
<?php
$location = bloginfo('url');
header( 'Location:' . $location ) ;
?>
You were using Javascript syntax for concatenation in PHP
<?php
$location = bloginfo('url');
header( 'Location:'.$location ) ;
?>
This should be your syntax.
Use a dot (.) not a plus (+).
header( 'Location:' . $location ) ;

how to replace a language identifier in a URL?

I need some help I have written the following preg_replace. The idea of the script is to get the language name from the domain name:
If I have a
http://www.domainname.com/nl/this/is/a/test/index.asp
I would like to strip the (nl) part from the domain name. The nl is a variable for languages so it could be:
http://www.domainname.com/nl/this/is/a/test/index.asp
http://www.domainname.com/fr/this/is/a/test/index.asp
http://www.domainname.com/de/this/is/a/test/index.asp
The above domains represents language directories...
<?php
$sitename = "http://" .$_SERVER["SERVER_NAME"];
$pagename = $_SERVER["PHP_SELF"]."this/is/a/test";
$language = "\/..\/";
$language1 = preg_replace("/$language/", "$1", "$pagename");
?>
I am only using the script where I know there will be a language directory.
The script above also removes the this/a/test/ the (is) from the url. (which tells me the script is greedy.
What would be the best method to grab the language from the url?
Can someone please provide me with some guidence.
Thanks
This is the script I came up using the advice below:
<?php
$mainurl = "http://" .$_SERVER["SERVER_NAME"];
$fullpagename = $_SERVER["PHP_SELF"];
$mainlanguage = preg_replace('%^/(\w+?)/.*$%', '$1', $_SERVER["REQUEST_URI"]);
$strippedpagename = preg_replace("/$mainlanguage\//", '$1', $_SERVER["REQUEST_URI"]);
?>
<?php echo "Full URL: ".$mainurl ?><br>
<?php echo "Full Page Name: ".$fullpagename ?><br>
<?php echo "Language: ".$mainlanguage ?><br>
<?php echo "Page Name No Language: ".$strippedpagename ?><br>
Exactly what I needed, or is there a more elegant way?
Maybe something like this:
$language = preg_replace('%^/(\w+?)/.*$%', '$1', $_SERVER["REQUEST_URI"])
Maybe more simple:
$language = reset( explode('/', substr($_SERVER["REQUEST_URI"],1) ) );
No need of regexp here.

Categories