Open In App

How to get complete current page URL in PHP ?

Last Updated : 06 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP. there is a superglobal variable that can provide you with the URL of the current working page. The $_SERVER is an inbuilt variable that can access the page URL, after that, you have to check that the URL is following which type of HTTP protocol.

What is Superglobal?

Superglobals are already defined variables by the PHP engine which can be used in any kind of scope. They are readily available at any one time.

We understand that by taking an example as given below:

Example 1: We can take the ternary operator for checking the working protocol and after that, we can add server host and request URL. 

PHP




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


Output:

Example 2: First we check the HTTP protocol then append that domain to the URL with the request URL. Finally, we get the current page URL.

PHP




<?php 
     
   $currentPageUrl = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
echo "Current page URL " . $currentPageUrl;
 
  ?>


Output:

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads