How to Get Current URL in PHP
In this tutorial, we will learn how to Get the Current URL in PHP. You can use the
$_SERVER
built-in variable to get the current page URL in PHP. The $_SERVER
is a super global variable, which means it is always available in all scopes.Use $_SERVER[‘HTTPS’] to check the protocol whether it is HTTP or HTTPS.
1 2 3 |
<?php $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; ?> |
Use $_SERVER[‘HTTP_HOST’] to get header from the current request and $_SERVER[‘REQUEST_URI’] to get URI of the current page.
1 2 3 |
<?php $currentURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?> |
If you want to get current page URL with query string, use this $_SERVER[‘QUERY_STRING’].
1 2 3 |
<?php $currentURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']; ?> |