Sometime during web development period we struggle on little things such as getting current URL. I also struggled to print current URL while coding this site.
We will use reserved variable in PHP named $_SERVER.Â
Current URL in PHP
It's easy to get current URL. You can use code below to get current page url in php
$uri = htmlspecialchars($_SERVER['REQUEST_URI']);
$host = $_SERVER['HTTP_HOST'];
if(isset($_SERVER['HTTPS'])){
   $http = 'https://';
} else{
   $http = 'http://';
};
$current_url = $http.$host.$uri;
echo $current_url;
?>
Explanation of Code:
$_SERVER['REQUEST_URI'] return file path just like /current-url-php.php . I used htmlspecialchars() function to just to protect script from XSS(Cross Site Scripting).
Now we got file path, $_SERVER['HTTP_HOST'] will return the host name like pujann.com.np . I don't have to use htmlspecialchars here because it's server generated.Â
The if statement is written to detect the http:// or https://. $_SERVER['HTTPS'] returns a non-empty value if the script was queried through the HTTPS protocol.
Finally we collect all three variable together and print it.
You can use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['REQUEST_URI'] if you just want to get just script URL. $_SERVER['REQUEST_URI'] will display GET parameter also.
Cheers!!!
Â