How to get current page URL in PHP?

In this tutorial, we will explain how to get current page URL in PHP. You can see get full URL in PHP. You will learn get absolute URL in PHP. You can understand a concept of get current page full URL in PHP.

To get the current page URL, PHP provide a superglobal variable $_SERVER. The $_SERVER is a built-in variable of PHP, which is used to get the current page URL. superglobal variable, means it is always available in all scope. If we want the full URL of the page, then we’ll need to check the protocol, whether it is https or http. 

Let’see below example here.

Example 1:
<?php
    if(isset($_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on') {
        $url = "https://";
        } else {
            $url = "http://";
        }
    // Append the host(domain name, ip) to the URL.
    $url.= $_SERVER['HTTP_HOST'];
    //Append the requested URL
    $url. = $_SERVER['REQUEST_URI'];
    
    echo $url;
?>

The isset() function is used here to check whether HTTPS is enabled or not.

How to get current page url in PHP using $_SERVER['PHP_SELF']

You can also use $_SERVER[‘PHP_SELF’] superglobal variable to get the path to the current PHP script.

<?php
$currentURL = "http://$_SERVER['HTTP_HOST']$_SERVER['PHP_SELF']";
?>

However, this will not include any query parameter or fragment identifiers.

Note that the $_SERVER[‘REQUEST_URI’] and $_SERVER[‘PHP_SELF’] variables may not be secure and can be manipulate by attackers. You should always sanitize and validate any input from these variables before using them in your code. 

<?php

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];

$currentPageURL = $protocol . "://" . $host . $_SERVER['REQUEST_URI'];

echo $currentPageURL;

?>

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *