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
- In what scenarios would using \n for line breaks be more appropriate than using the br-tag in PHP code?
- What potential pitfalls can arise when using a switch statement in PHP for including different pages?
- What are the potential reasons for not receiving a notification when a new user registers through a plugin in PHP?