How to Retrieve the Full URL, Including Mask Modifications, in PHP
When creating a dynamic website, it's crucial to access the full URL that users see in their web browsers. However, traditional methods like $_SERVER['PHP_SELF'] might not always suffice due to the use of URL masks in .htaccess. To resolve this issue, $_SERVER['REQUEST_URI'] provides a comprehensive solution.
Using $_SERVER['REQUEST_URI']
To obtain the full URL as it appears in the address bar, use the following code:
$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
This code combines $_SERVER['HTTP_HOST'] with $_SERVER['REQUEST_URI'], which holds the path and query string. It effectively generates the complete URL, including any mask modifications applied in .htaccess.
Supporting HTTP and HTTPS with Protocol Inclusion
To ensure support for both HTTP and HTTPS protocols, modify the code as follows:
$actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
This updated code checks the $_SERVER['HTTPS'] value and adds the appropriate protocol based on its presence.
Security Considerations
It's important to note that these techniques may pose security risks as HTTP_HOST and REQUEST_URI can be manipulated by the client or server. Proper input validation and sanitization are essential before using these values in any security-related scenarios.
The above is the detailed content of How to Get the Complete URL, Including .htaccess Modifications, in PHP?. For more information, please follow other related articles on the PHP Chinese website!