Skip to main content

How to Get the Full URL of Current Page in PHP

By SamK
Current URL in PHP

In this tutorial, we'll learn how to get the full URL of the currently opened page in PHP.

Everything is explained step-by-step below:

1. First of all we need a variable to store the URL. Lets say $url is the variable.

2. Next we need to check if the website is using http:// or https://, like:

if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    $url = "https://";
} else {
    $url = "http://"; 
}

3. The next step is to find the host, which is a domain name or IP address, and append it to the $url variable value we saved above, like:

$url .= $_SERVER['HTTP_HOST']; 

4. The next step is to find the currently opened resource or page path and append it to the $url variable value, like:

$url .= $_SERVER['REQUEST_URI']; 

5. Final step is to combine the code and print the full URL like:

<?php 
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    $url = "https://"; 
} else {
    $url  = "http://"; 
    $url .= $_SERVER['HTTP_HOST']; 
	$url .= $_SERVER['REQUEST_URI']; 
	// Print the URL
	echo $url;
} 
?>

Alternative Method

<?php
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; 
echo $url;
?> 
Category(s)
Topic(s)