How can the use of get_headers() function help in debugging issues related to URL redirects in PHP?

When dealing with URL redirects in PHP, it can sometimes be challenging to determine the final destination of a URL due to multiple redirects happening behind the scenes. The get_headers() function in PHP can help by retrieving the headers of a URL, including any redirect information. By inspecting the headers returned by this function, you can track the chain of redirects and identify the final destination URL.

$url = 'https://example.com';
$headers = get_headers($url, 1);

// Loop through the headers to find the final destination URL
$finalUrl = $url;
foreach ($headers as $header) {
    if (strpos($header, 'Location') !== false) {
        $finalUrl = $header;
    }
}

echo 'Final URL: ' . $finalUrl;