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:
<?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
Or, we can also get the full URL of current page using another way given in the next example.
<?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
To get only name of the current page opened at browser, see the below example:
<?php $curPageName = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); echo "The current page name is: ".$curPageName; echo "</br>"; ?>
Output