How to Get the Full URL of Current Page in PHP

Category:

Tutorial Topic:

In this tutorial we'll learn how to get the full url of currently opened page via 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;
?>