What best practices should be followed when working with cURL in PHP to ensure accurate retrieval of redirected URLs?

When working with cURL in PHP to retrieve redirected URLs, it is important to set the CURLOPT_FOLLOWLOCATION option to true to allow cURL to follow redirects automatically. Additionally, you should set the CURLOPT_MAXREDIRS option to limit the number of redirects that cURL will follow to prevent potential infinite loops.

$url = 'http://example.com';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // Set maximum number of redirects to follow

$response = curl_exec($ch);

if($response === false) {
    echo 'Error: ' . curl_error($ch);
} else {
    echo 'Redirected URL: ' . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}

curl_close($ch);