Select Page

Want to know what is the current URL of the page in php ?? It’s really easy to get current URL of page in php and I will simplify it more for you !!. Therefore my today’s post is especially for php developer.

Quick Solution To Get Current URL Of Page

If you are looking for a quick answer you can just use the below code in php for getting current URL.

$current_url = (isset($_SERVER[‘HTTPS’]) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ;

Yes, this one line of code will work like a charm for you !!

Explanation Of How it Works

Now if you want the explanation then you may read this else you are good to go with the above given code.

For grabbing the current page URL we need to use the $_SERVER variable. $_SERVER is a superglobal variable so it will be available in all scopes i.e you can use it anywhere in your php code.

Algorithm Used For Getting Current URL

First, let’s see the algorithm that we have used –

Step 1. Getting the proper HTTP protocol

Step 2. Getting the HTTP  host

Step 3. Getting The Requested URL

Step 4. Joining the HTTP protocol, HTTP host And Requested URL  together into one variable.

Proper Code With Explanation

Now that you know the algorithm that we have used for getting the current URL we can now dive into the code.

I have made a function of getting the URL IN PHP.


function get_current_url($query = true ){
$http_protocol = "http" ;
$http_protocol = "https" ; // The $http_protocol will change to https if https is used

$current_url = $http_protocol."://".$_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’] ;

$current_url = str_replace(‘?’.$_SERVER[‘QUERY_STRING’],"",$current_url) ;

return $current_url ;

Just copy the above the function into your code and you are good to go.

Calling The Get Current URL Function

Whenever you need to get the current URL of the page just call the function get_current_url() and you will get the URL.
like this –

$current_url = get_current_url();

Get Current URL Without Query String

Want to get the current URL without the query string ?? don’t worry our function is already optimized for that.
just add a false parameter to the function and it will strip off the query string for the current URL.
like this –

$current_url = get_current_url(false);

And that’s it for now in case if you have any doubts or queries related to getting current URL in php feel free to ask me in the comments section below.

And if this post helped you please do share it will your other web developer friends.

Need Help? Chat with us
Share This