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);
Related Questions
- What are some best practices for structuring PHP code to maintain readability and avoid errors like unexpected 'case' statements?
- How can PHP be utilized to retrieve and display data from a database in a structured manner?
- How can deprecated mysql_* functions be replaced with more modern alternatives like PDO or mysqli_* in PHP code?