Get Full URL of Current Page in PHP

The PHP $_SERVER superglobal is an array containing information such as headers, paths, and script locations which is always available (though has different contents if running PHP on the command line). In this case we're using PHP in a web server context, and we want to get the URL of the current page.

We'll use two entries from this array to help get the URL of the current page:

    Contents of the Host: header from the current request, if there is one.
    The URI which was given in order to access this page; for instance, '/index.html'. 

Here is the example PHP snippet:

$url = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

If you need to support both HTTP and HTTPS dynamically, you can try incorporating the $_SERVER['HTTPS'] variable into the snippet.

    Set to a non-empty value if the script was queried through the HTTPS protocol. 

For example:

$url = ! empty($_SERVER['HTTPS']) ? 'https' : 'http'.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

Here is the PHP documentation for the $_SERVER superglobal: