PHP: Get full URL of current page.

This is a tutorial on how to get the full HTTP URL of the current web page using PHP. To do this, we will create a custom function that pieces together some of the server information that is available in the $_SERVER superglobals array.

Take a look at the following PHP function:

 * Get the HTTP(S) URL of the current page.
 * @param $server The $_SERVER superglobals array.
 * @return string The URL.
function currentUrl($server){
    //Figure out whether we are using http or https.
    $http = 'http';
    //If HTTPS is present in our $_SERVER array, the URL should
    //start with https:// instead of http://
        $http = 'https';
    //Get the HTTP_HOST.
    $host = $server['HTTP_HOST'];
    //Get the REQUEST_URI. i.e. The Uniform Resource Identifier.
    $requestUri = $server['REQUEST_URI'];
    //Finally, construct the full URL.
    //Use the function htmlentities to prevent XSS attacks.
    return $http . '://' . htmlentities($host) . '/' . htmlentities($requestUri);

$url = currentUrl($_SERVER);
echo $url;

To construct the URL, we use three different variables.

  • We check to see if HTTPS exists. If “HTTPS” does exist in the $_SERVER array, then we assume that the site is using SSL and that the URL should start with HTTPS instead of HTTP.
  • Next, we get the HTTP_HOST. This will give us the current domain name and/or sub-domain.
  • Finally, we get the REQUEST_URI. This provides us with the file (and folder path) of the web page that is being requested. Note that any query string / GET parameters will also be included in this.

You may have noticed the fact that I used the PHP function htmlentities on both HTTP_HOST and REQUEST_URI. This is to prevent XSS attacks, as both variables can be modified by the client. By using htmlentities, we can guard against the possibility of a malicious attacker injecting JavaScript code into these variables.

Hopefully, my readers will find the function above to be useful.