How to Get Current URL in PHP

June 18, 2020
PHP
get current url in php

Full Code

Here’s the full code that you can use:

$protocol = (isset($_SERVER['HTTPS'])) ? "https://" : "http://";
$URL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

Definitions

Here are the definitions for the above code.

  • $protocol checks if the current path contains HTTP or https protocol
  • $_SERVER[‘HTTP_HOST’] as per standard definition is the contents of the Host: header from the current request.
  • $_SERVER[‘REQUEST_URI’] gets the full path of the page.

Example

I am running on a localhost server, and I have the current path as http://localhost/howto/edit.php?id=4.

Running the above code, will give me the ff values:

$protocol = http://

$_SERVER[‘HTTP_HOST’] = localhost

$_SERVER[‘REQUEST_URI’] = /howto/edit.php?id=4

$URL = http://localhost/howto/edit.php?id=4

That ends this tutorial. Happy Coding!

Facebook Comments

Leave a Reply

Your email address will not be published.