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 the $_SERVER variable to get the current page URL in PHP. The following example code shows how to get the current full URL with query string using the $_SERVER variable in PHP.

Use $_SERVER['HTTPS'] to check the protocol whether it is HTTP or HTTPS.

$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.

$currentURL $protocol $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

If you want to get current page URL with query string, use $_SERVER['QUERY_STRING'].

$currentURL $protocol $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];

1 Comment

  1. Yogesh Singh Said...

Leave a reply

keyboard_double_arrow_up