Get the current page URL in PHP

By Faruque Ahamed Mollick

Here in this tutorial, I am going to show you another code snippet which will show you how to get the current page URL using PHP.

Well, there is a super global variable available in PHP that is $_SERVER. Using this super global variable you can easily get the current page URL.

Here is two example usage of this variable:

  • $_SERVER[‘HTTP_HOST’] will get the host of the web page. It will simply return the domain or IP address in which URL you are visiting. For this website, the host will be www.codespeedy.com.
  • $_SERVER[‘REQUEST_URI’] will return the rest of the part of the domain when you are visiting in a URL. For example you are in this post and $_SERVER[‘REQUEST_URI’]; will return get-the-current-page-url-in-php.

Now let’s see the complete code that returns the complete URL of a current web page.

PHP code to get the current page URL

Below is a PHP function that returns the current page URL:

<?php

function currentUrl() {
   $httpHost = $_SERVER['HTTP_HOST'];
   $requestUrl = $_SERVER['REQUEST_URI'];

   if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
       isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
       $protocol = 'https://';
    }
    else {
       $protocol = 'http://';
    }
    $pageUrl = $protocol."".$httpHost."".$requestUrl;
    return $pageUrl;
}
?>

After using the above function, suppose you want to display the current page URL on the same web page. To do that we just need to use the simple code that is given below:

echo currentUrl();

Now we have the current page URL in currentUrl() function and we can do whatever we like with it. We can store it in a database table or can send it to anywhere or just simply display on web page. This is really so useful code snippets that I have shown you in this post.

By sending the URL in your database, you will know how many visits your website is getting. After some improvement of the code, you will be able to do lots of more like the time of visited pages,  IP of the users that visited the pages and much more.

I hope you liked this tutorial. helping our readers is the main aim of our blog. Please let me know if you want to know about anything related to this post.

Leave a Reply

Your email address will not be published. Required fields are marked *