Are there best practices for handling redirects when using file_get_contents or cURL in PHP scripts?

When using file_get_contents or cURL in PHP scripts, it's important to handle redirects properly to ensure that the final response is retrieved. This can be done by setting the CURLOPT_FOLLOWLOCATION option to true in cURL or using the stream context with the 'http' key set to follow redirects in file_get_contents.

// Using cURL with CURLOPT_FOLLOWLOCATION option to handle redirects
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
curl_close($ch);

// Using file_get_contents with stream context to handle redirects
$context = stream_context_create(['http' => ['follow_location' => 1]]);
$response = file_get_contents($url, false, $context);