In PHP Get Current URL, I have explained how get current page URL with parameters in PHP. To Get Current URL of the Page, we can use $_SERVER environment variables.
Below is the list of useful environment variables for getting current Page URL.
$_SERVER['HTTP_HOST'] => Host name from the current request. $_SERVER['HTTP'] => Set to a non-empty value if the protocol is HTTP $_SERVER['HTTPS'] => Set to a non-empty value if the protocol is HTTPS $_SERVER["SERVER_PORT"] => Server port. Default is: 80 $_SERVER['REQUEST_URI'] => The URI to access this page; For example, '/index.php'.
1). We can get protocol schema
$schema = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
2). If the server is running on standard port(80,443), full URL path becomes:
$schema.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; //EX: http://www.hayageek.com/test.php
3). If the server is running on non standard port, full URL Becomes
$schema.$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; //EX: http://www.hayageek.com:8080/test.php
Note: In PHP, We can not read URL path after hash(#) tag. Because browser does not send the hash data to server. You can get #tag data only with JavaScript.
Combing all, below is the function for getting current web page URL in PHP
function getCurrentURL() { $currentURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://"; $currentURL .= $_SERVER["SERVER_NAME"]; if($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") { $currentURL .= ":".$_SERVER["SERVER_PORT"]; } $currentURL .= $_SERVER["REQUEST_URI"]; return $currentURL; }
Usage:
echo getCurrentURL();
Reference: PHP Documentation