To follow HTTP redirects in a cURL request using PHP, you can make use of the CURLOPT_FOLLOWLOCATION option that will automatically follow any redirects encountered during the request. Here's an example:
$url = 'http://example.com'; // Your target URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Enable redirect following
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response instead of outputting it
$response = curl_exec($ch);
curl_close($ch);
echo $response; // Output or process the response
In the above code, the curl_setopt()
function is used to set the desired options for the cURL request. The CURLOPT_FOLLOWLOCATION
option is set to true, which enables automatic following of redirects. The CURLOPT_RETURNTRANSFER
option is also set to true to ensure that the response is returned as a string instead of being directly outputted.
After executing the cURL request with curl_exec()
, you can process or output the response as desired.
Note: By default, cURL follows up to 20 redirects. If you want to change this limit, you can set the CURLOPT_MAXREDIRS
option to a different value before executing the request.