How can PHP be used to handle HTTP redirects and extract the destination URL from the headers?

To handle HTTP redirects and extract the destination URL from the headers in PHP, you can use the `get_headers()` function to retrieve the headers of a URL. By checking for the "Location" header in the response, you can extract the destination URL of the redirect. This can be useful for scenarios where you need to follow redirects programmatically and obtain the final URL.

function getFinalRedirectUrl($url) {
    $headers = get_headers($url, 1);

    if (isset($headers['Location'])) {
        if (is_array($headers['Location'])) {
            // If multiple redirects, get the last one
            return end($headers['Location']);
        } else {
            return $headers['Location'];
        }
    }

    return $url; // Return original URL if no redirect
}

$initialUrl = "http://example.com";
$finalUrl = getFinalRedirectUrl($initialUrl);
echo "Final URL after following redirects: " . $finalUrl;