- Instant help with your Php coding problems

PHP get current page URL

In PHP there are some built-in global variables that make getting the current URL process quite simple. You can get every piece of information about the current URL using the $_SERVER  superglobal array.
You can get the domain name, the script name, the URL parameters, and any variation of these.
After this introduction let’s see how it works. First of all try to figure out a complex URL structure like this:

http://www.demo.com/test/myscript.php?city=Dallas&start=10

Let’s take this URL to pieces:

  •     http - This is the protocol
  •     www.demo.com - This is the hostname.
  •     test - This is a directory
  •     myscript.php - This is the actual script name
  •     name=Bob - This is the first URL parameter (city) and it’s value (Dallas)
  •     start=10 - This is the second URL parameter (start) and it’s value (10)

And now lets’s try to build the same URL with PHP. 

Get the protocol

The URL protocol can be read out from the $_SERVER['SERVER_PROTOCOL']  variable. 

echo $_SERVER['SERVER_PROTOCOL'];

However, if you check the value you can find that is not simply HTTP or HTTPS but a string like this: HTTP/1.1

So we need some string manipulation to get a clean protocol string:

$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') 
                === FALSE ? 'http' : 'https';

Get the hostname

As the next step, we need to figure out the hostname. This is in the $_SERVER['HTTP_HOST'] . You can read it simply like this:

$host = $_SERVER['HTTP_HOST'];

Get the directory and script name

The $_SERVER['SCRIPT_NAME']  contains the full path with the name of the actual php script as you can see here:

$script = $_SERVER['SCRIPT_NAME'];

Get URL parameters

The last part of the current URL is in the $_SERVER['QUERY_STRING']  and can be accessed similar to the others:

$params = $_SERVER['QUERY_STRING'];

Get the actual URI

If the protocol and the hostname are not important for you but only the path, script name, and the URL parameters then you can use simply the $_SERVER['REQUEST_URI']  as follows:

$uri = $_SERVER['REQUEST_URI'];

Get the current page URL

So finally, to get the current page URL in PHP looks like this:

$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') 
                === FALSE ? 'http' : 'https';
$host     = $_SERVER['HTTP_HOST'];
$script   = $_SERVER['SCRIPT_NAME'];
$params   = $_SERVER['QUERY_STRING'];
 
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
 
echo $currentUrl;

Note: Almost all modern webserver with PHP supports the used $_SERVER variables, you need to know: “The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these.”  See PHP $_SERVER manual

Share "PHP get current page URL" with your friends