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.';
}