How to set the maximum number of redirects to follow in a cURL request in PHP?

To set the maximum number of redirects to follow in a cURL request in PHP, you can use the CURLOPT_FOLLOWLOCATION and CURLOPT_MAXREDIRS options in conjunction.

Here's an example of how you can do it:

// Initialize cURL $ch = curl_init(); // Set the URL $url = "http://example.com"; curl_setopt($ch, CURLOPT_URL, $url); // Enable automatic following of redirects curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Set the maximum number of redirects to follow curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // Change 5 to your desired maximum // Other cURL options if needed... // Execute the cURL request $response = curl_exec($ch); // Check for errors if (curl_errno($ch)) { echo 'cURL Error: ' . curl_error($ch); } // Close cURL curl_close($ch);

In this example, we set CURLOPT_FOLLOWLOCATION to true to allow cURL to automatically follow any redirects encountered. Then, we set CURLOPT_MAXREDIRS to 5 to specify the maximum number of redirects to follow. You can change the 5 to your desired maximum number.

Finally, you can add other cURL options if needed for your specific request. Remember to check for errors using curl_errno and close the cURL session with curl_close.