How to Get the Current Page URL in PHP

09/04/2021

Contents

In this article, I will introduce how to get current page URL in PHP.

The $_SERVER Superglobal variable

To get the URL of the current page in PHP, use the $_SERVER superglobal variable.

$_SERVER contains information such as headers, paths, and script locations.

This superglobal variable can be referenced anywhere in your PHP program.

Usage

Get the current page name

$_SERVER["REQUEST_URI"]

You can get the current page name excluding the protocol name such as http or https and the domain name (host name) of the server.

Get the hostname of the current page

$_SERVER["HTTP_HOST"]

You can get the domain name of the server.

Get the protocol name of the current page

(empty($_SERVER["HTTPS"]) ? "http://" : "https://")

You can get the protocol name such as http or https.

If the current page’s protocol is not https, $_SERVER["HTTPS"] is empty, so http:// is returned.

Sample

Sample URL
http://localhost/sample/sample123.php
Sample Code
<?php
echo $_SERVER['REQUEST_URI'];
echo $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
echo (empty($_SERVER["HTTPS"]) ? "http://" : "https://") . 
$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
?>
Result
/sample/sample123.php
localhost/sample/sample123.php
http://localhost/sample/sample123.php