How to Get Current URL in PHP
In this post we will show you How to Get Current URL in PHP. $_SERVER is a superglobal variable in PHP, that provides information about headers, paths, and script locations. Besides the various uses of $_SERVER variable, it helps to get current page URL in PHP.
You can use $_SERVER variable to get current page URL in PHP. The following example code shows how to get current full URL with query string using $_SERVER variable in PHP.
Use $_SERVER['HTTPS']
to check the protocol whether it is HTTP or HTTPS.
1 2 |
$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 |
$currentURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; |
If you want to get current page URL with query string, use $_SERVER['QUERY_STRING']
.
1 |
$currentURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']; |
(Visited 745 times, 1 visits today)