Register Login

Get the Current URL of Webpage in PHP

Updated Dec 08, 2020

If you are browsing a webpage or a web application, PHP will store a lot of useful information in the background. This information gets stored in PHP’s super-global variables. These are pre-defined variables that are available in all types of scope. You can use these variables to obtain the current URL of the web page.

How to get the current full URL?

The super-global variable called $_SERVER can fetch you the current URL of a website. Some of the properties of the variable that you can access include HTTP_USER_AGENT, HTTP_HOST and HTTP_ACCEPT. For the URL, we will access the HTTP_HOST and REQUEST_URl property.

But you need to check the protocol of the website, if it is HTTP or HTTPS.

Example Code

<?php
// Get Protocol https or http
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
// Append Host Name and requested resource location
$finalurl .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $finalurl;
?>

Output

https://www.stechies.com/current-url.php?v=1

Explanation

In the code above, the super-global variable $_SERVER is used to access the property ‘HTTPS’ to check and fetch the protocol used for the site. The value is assigned to a variable called $protocol.

Then, the $_SERVER variable is used again to access the 'HTTP_HOST' property to obtain the host name. The property REQUEST_URl is used to fetch URL of the current webpage. Both the information is appended using the concatenation operator (.) and stored in the variable $finalurl. This value is printed out using the echo statement.          

Function to display full URL

Example 1

<?php
function displayfullurl(){
$finalurl = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://".$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $finalurl;
}
displayfullurl();
?>

Output

https://www.stechies.com/current-url.php?o=p

Explanation 

This code checks whether the current site runs on HTTP or HTTPS, using the $_SERVER. Then, with that value (which can be HTTPS or HTTP), the current hostname and URL of the site is appended. The combined value of all that information gives us the full URL of the website. 

Example 2

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

Output

https://www.stechies.com/current-url.php?o=p

You can use this code to get the current URL of the webpage when you know that your site is running on HTTP or HTTPS.  


×