Is there a recommended method or code example to handle URL redirection detection in PHP?
When handling URL redirection detection in PHP, one common approach is to check the HTTP response headers for any redirection status codes (e.g., 301 or 302). This can be done using the PHP function get_headers() to retrieve the headers of a URL and then checking for any Location header that indicates a redirection.
$url = 'https://example.com';
$headers = get_headers($url, 1);
if (isset($headers['Location'])) {
$redirectUrl = $headers['Location'];
echo 'Redirected to: ' . $redirectUrl;
} else {
echo 'No redirection detected.';
}
Related Questions
- What are common causes of the error message "Warning: Cannot modify header information - headers" in PHP?
- What are some best practices for implementing If-Abfrage with character sequence checks in PHP?
- What are best practices for securely executing external commands in PHP scripts, especially when interacting with Windows services?