How to get the current page URL in PHP

Get current page URL in PHP

There are numerous ways to get page URLs in PHP. In this article, we will see how to get the current page URL in PHP.

$_SERVER – Super Global Variable

PHP provides a built-in super global variable known as $_SERVER, which is used to get the server and environment execution information. We can also use this variable to get the current page URL.

With PHP we can get the current page URL in a single line of code. For example:

<?php
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    echo $url;
?>

Since a server can have both protocols (HTTP or HTTPS) and also the ports, the more efficient way of fetching the current page URL is:

<?php
	// function to get current page URL in PHP
	function getCurrentPageUrl() {
	    // default protocol
	    $pageURL = 'http';

	    // check if protocol is with SSL
	    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
	    	$pageURL .= "s";
	    }
	    
	    $pageURL .= "://";
	    
	    // check for port and create URL
	    if ($_SERVER["SERVER_PORT"] != "80") {
	        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	    } 
	    else {
	        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	    }
	    
	    return $pageURL;
	}

	echo getCurrentPageUrl();
?>

This script will not only checks the protocol but also if the URL contains a port.

Some more examples:

We will cover more examples in the following section:

The HTTP_HOST is used to get the host or domain name. For example:

<?php  
    $domain = $_SERVER['HTTP_HOST'];  
    echo $domain;
?> 

Get query string (the bit after the ? in a URL), that part is in this variable:

<?php
	$query_string = $_SERVER['QUERY_STRING'];
	echo $query_string;
?>

If you want just the parts of the URL after http://www.domain.com, the following will serve the purpose:

<?php 
	$url_except_domain = $_SERVER['REQUEST_URI']; 
	echo $url_except_domain;
?>

If you need the name of the current PHP page opened in the browser, the following code will be useful:

<?php  
    $current_page = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/") + 1);  
    echo $current_page;
?>  

In the next article, we will see how to get the current page URL in WordPress.

Tags:

Related Posts