Home >Backend Development >PHP Tutorial >How Can I Get the Complete, Browser-Displayed URL in PHP, Accounting for .htaccess and Security?
Get the Complete URL in PHP
When attempting to retrieve the full URL using the code snippet $actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];, one faces a limitation due to .htaccess masking. The returned URL may not accurately reflect the URL displayed in the browser's navigation bar.
To obtain the exact URL as it appears in the browser, utilize the $_SERVER['REQUEST_URI'] variable. The following code illustrates its usage:
$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
For flexibility across both HTTP and HTTPS protocols, employ the following code:
$actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Security Considerations
It's important to note that this code has security implications. The client and server can modify HTTP_HOST and REQUEST_URI to arbitrary values. Adequate sanitization and input validation are crucial to prevent these values from being exploited in security contexts (CWE-20).
The above is the detailed content of How Can I Get the Complete, Browser-Displayed URL in PHP, Accounting for .htaccess and Security?. For more information, please follow other related articles on the PHP Chinese website!