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 (3) Add New Comment
sklep2024-03-02 6:24 PM

My programmer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using WordPress on various websites for about a year and am worried about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any help would be greatly appreciated! I saw similar here: dobry sklep and also here: sklep

Reply
spectralex.top2024-02-28 11:47 AM

You actually make it appear so easy with your presentation but I to find this matter to be really something which I think I might never understand. It kind of feels too complicated and extremely huge for me. I'm taking a look forward in your subsequent publish, I'll try to get the hold of it! I saw similar here: najlepszy sklep and also here: dobry sklep

Reply
dobry sklep2024-02-24 5:41 AM

Wow, amazing blog layout! How lengthy have you been blogging for? you made blogging glance easy. The overall glance of your website is excellent, let alone the content material! You can see similar: sklep internetowy and here najlepszy sklep

Reply