PHP has special variables called “super global variables” that are built-in variables and are available in all scopes anytime we want.
We are going to use PHP Superglobal $_SERVER to get that information.
$_SERVER variable holds information about paths, headers, script locations etc.
We can use the $_SERVER variable like this example:
echo $_SERVER['SERVER_NAME']
//www.yogeshchauhan.com
Now let’s get the full URL in small pieces. The first thing we need to do is check if the URL is secure or not.
How to check if the URL is HTTP or HTTPS?
We can use $_SERVER[‘HTTPS’] to get that information from the super global $_SERVER.
Just like this:
if(isset($server['HTTPS'])){
$http_info = 'https';
} else {
$http_info = 'http';
}
How to get the host name?
The next thing is to get the host name. For that we can use $server[‘HTTP_HOST’] to get that info.
$host_name = $server['HTTP_HOST'];
Till this point we got the URL of the homepage of any website. But we need the complete URL so let’s get the third part.
We need the part after the domain name ends which is called URI or Uniform Resource Identifier. We can use $server[‘REQUEST_URI’] to get that part.
Just like this:
$file_path = $server['REQUEST_URI'];
Now, we all that we need to make the complete URL of any page. Let’s make a function out of all those parts so that we can use it anywhere on the website by simply calling it.
Function to get the full URL of current page in PHP
I’m using htmlentities function to convert characters to HTML entities which is similar to htmlspecialchars() function.
function get_the_current_url($server){
if(isset($server['HTTPS'])){
$http_info = 'https';
} else{
$http_info = 'http';
}
$host_name = $server['HTTP_HOST'];
$file_path = $server['REQUEST_URI'];
return $http_info . '://' . htmlentities($host_name) . '/' . htmlentities($file_path);
}
This is how you can call the function after placing it at appropriate location in the folder structure.
// store the URL in a variable
$current_url = get_the_current_url($_SERVER);
echo $current_url;
// or simply print it
echo get_the_current_url($_SERVER);
HTTPS server Superglobal variables