Friday, March 2, 2018

How to get current page URL using PHP

In this tutorial, we are going to discuss how to get current page URL using PHP$_SERVER is a super global variable, which is always available in all scopes. We will use $_SERVER variable to get the current page URL. It is an array contains various information such as, headers, document path, script location, request method etc.




Explanation about some useful $_SERVER variable :
  1. $_SERVER['HTTP_HOST'] : Contents of the Host header from the current request, if there is one.
  2. $_SERVER['PHP_SELF']  : The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://skptricks.com/post/php-tutorial.php would be /post/php-tutorial.php.
  3. $_SERVER['QUERY_STRING'] : If a page is accessed via any query string, $_SERVER['QUERY_STRING'] fetches that query string.This is a actual URL http://localhost/skptricks/check current page url/currentPageURL.php?jj=kkkk after the $_SERVER['QUERY_STRING'] operation would be jj=kkkk .


Get Current Page URL in PHP :

Lets see the following simple PHP function with help of that you can get the current page URL with or without the query string as per your need.

<?php
function getCurrentPageURL($queryString = false) {
   $port = $_SERVER['SERVER_PORT'];
            
   $url  = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $port == 443) ? "https://" : "http://";
   $url .= $_SERVER['HTTP_HOST'];
   $url .= ($port == '80' || $port == '443' ? '' :  ':' . $port);
   $url .= $_SERVER['PHP_SELF'];
   $url .= ($queryString == true ? '?' . $_SERVER['QUERY_STRING'] : '');
            return $url;
}
// get URL without query string
echo "<b>Current page URL without query string :</b> " . getCurrentPageURL();
echo '<br>';
// get URL with query string
echo "<b>Current page URL with query string :</b> " . getCurrentPageURL(true);
?>

Output: 
Current page URL without query string : http://localhost/skptricks/check current page url/currentPageURL.php
Current page URL with query string : http://localhost/skptricks/check current page url/currentPageURL.php?jj=kkkk

This is all about fetching current page URL using PHP. Hope you like this simple example. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

Download Link :
https://github.com/skptricks/php-Tutorials/tree/master/How%20to%20get%20current%20page%20URL%20using%20PHP



No comments:

Post a Comment