Clue Mediator

Get current page URL in PHP

📅February 19, 2020
🗁PHP

In this tutorial, we will show you how to get current page url and parts i.e. path, domain, query strings, etc in php.

Get the full URL in PHP, Get current URL path in PHP, How to Get Current Page URL in PHP, PHP: $_SERVER, PHP: Get full URL of current page, How to Get The Full URL and Parts In PHP, Get full web page URL from address bar, PHP Get Current URL Full Path, Get current URL excluding parameters in php, PHP to get URL of my script.

Checkout more articles on PHP

In PHP, we can get current page url using `$_SERVER` built-in superglobal variable. Assume that the current url is `https://www.cluemediator.com/category/php/blog.php`.

We will learn the functions below to get the parts and full url of the current page.

  1. $_SERVER['HTTPS']
  2. $_SERVER['HTTP_HOST']
  3. $_SERVER['REQUEST_URI']
  4. $_SERVER["QUERY_STRING"]

1. $_SERVER['HTTPS']

Using `$_SERVER['HTTPS']`, we can check the protocol is http or https.

$protocol =  (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://");
echo $protocol;

// Output: https://

2. $_SERVER['HTTP_HOST']

To get Host (Domain name), we will use `$_SERVER['HTTP_HOST']`.

$host = $_SERVER['HTTP_HOST'];
echo $host;

// Output: www.cluemediator.com

3. $_SERVER['REQUEST_URI']

To get the full path of a page, we will use `$_SERVER['REQUEST_URI']`.

$path = $_SERVER['REQUEST_URI'];
echo $path;

// Output: /category/php/blog.php

Finally to get full current page url, we can write the code like below.

$protocol =  (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://");

$getUrl = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $getUrl;

// Output: https://www.cluemediator.com/category/php/blog.php

4. $_SERVER["QUERY_STRING"]

If you want to get query from the url, you can use `$_SERVER["QUERY_STRING"]`. let's take one example if current url is `https://www.cluemediator.com/category/php/blog.php?id=1&cat=2`.

$query = $_SERVER["QUERY_STRING"];
echo $query;

// Output: id=1&cat=2

That’s it for today.
Thank you for reading. Happy Coding!