2018-12-10 Pujan Niroula 1 Minute(s) Read

Get Current Page URL in PHP

img-thumbnail current url php.jpg

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!!!

 

Tags:php, how to,
Comments (0) Add New Comment
No comments, Be first one to commment!