PHP: Get full URL of current page.

In this tutorial, we will show you how to get the full URL of the current page using PHP.

We will also create a custom function that you can easily copy and paste into your own project.

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){

    //Determine if 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;

In order to build the current URL, we need to use three server variables:

  1. Firstly, we check to see if HTTPS exists. If “HTTPS” does exist in the $_SERVER array, then we can presume that the site is using SSL. As a result, our URL will need to start with HTTPS instead of HTTP.
  2. Next, we get the HTTP_HOST variable. This will give us the name of the domain and/or subdomain.
  3. Finally, we get the REQUEST_URI. This provides us with the file and folder path of the URL. This string will also include the query string and its GET parameters.

In the PHP code above, we used the function htmlentities on both HTTP_HOST and REQUEST_URI.

We did this in order to prevent XSS attacks. The problem with these variables is that they come from the client.

Therefore, we have no way of knowing if the user has tampered with the URL or not.

By using htmlentities, we can guard against the possibility of an attacker injecting JavaScript code into these variables.