How to make multiple parallel cURL requests in PHP?

To make multiple parallel cURL requests in PHP, you can use multi-cURL functionality, which allows you to execute multiple requests simultaneously. Here is an example code snippet that demonstrates how to achieve this:

// Create array of cURL handles $curlHandles = array(); // Create multi-cURL handle $multiCurlHandle = curl_multi_init(); // URLs to make requests to $urls = array( 'https://example.com/1', 'https://example.com/2', 'https://example.com/3', // Add more URLs as needed ); // Loop through URLs and create cURL handles foreach ($urls as $url) { $curlHandle = curl_init($url); // Configure cURL options curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); // Add additional options as needed // Add cURL handle to array $curlHandles[] = $curlHandle; // Add cURL handle to the multi-cURL handle curl_multi_add_handle($multiCurlHandle, $curlHandle); } // Execute the multi-cURL requests do { $multiCurlResult = curl_multi_exec($multiCurlHandle, $running); } while ($multiCurlResult == CURLM_CALL_MULTI_PERFORM); // Loop through the cURL handles and process their responses foreach ($curlHandles as $curlHandle) { // Wait for the cURL handle to finish curl_multi_select($multiCurlHandle); // Get the cURL handle's result $result = curl_multi_getcontent($curlHandle); // Process the result as needed // Remove the cURL handle from the multi-cURL handle curl_multi_remove_handle($multiCurlHandle, $curlHandle); } // Close the multi-cURL handle curl_multi_close($multiCurlHandle);

This code uses a loop to create multiple cURL handles, each configured with its own URL and options. These handles are then added to the multi-cURL handle using the curl_multi_add_handle function. The requests are executed using the curl_multi_exec function, and the results are processed in a separate loop.

Note that this is a basic example, and you may need to adjust it based on your specific requirements, such as handling errors, setting request headers, or parsing the responses.