How to get current page URL in PHP?

To get the current page URL, PHP provides a superglobal variable $_SERVER. The $_SERVER is a built-in variable of PHP, which is used to get the current page URL. It is a superglobal variable, means it is always available in all scope.

If we want the full URL of the page, then we'll need to check the protocol (or scheme name), whether it is https or http. See the example below:

snippet
<?php
	if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') 
   		 $url = "https://"; 
	else
   		 $url = "http://"; 
	// Append the host(domain name, ip) to the URL. 
	$url.= $_SERVER['HTTP_HOST']; 
  
	// Append the requested resource location to the URL 
	$url.= $_SERVER['REQUEST_URI'];  
	
	echo $url;
  ?>

Output

Output
How to get current page URL in PHP
Note
Note: The isset() function is used here to check whether HTTPS is enabled or not. It checks whether a variable exists or not.

Or, we can also get the full URL of current page using another way given in the next example.

snippet
<?php
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$CurPageURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo "The URL of current page: ".$CurPageURL;
?>

Output

Output
How to get current page URL in PHP 1

To get only name of the current page opened at browser, see the below example:

snippet
<?php
	$curPageName = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
	echo "The current page name is: ".$curPageName;
	echo "</br>";
  ?>

Output

Output
How to get current page URL in PHP 1
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents