Are there best practices for handling multiple cURL requests in a single PHP file?

When handling multiple cURL requests in a single PHP file, it is recommended to use multi-cURL functions provided by PHP to improve performance and efficiency. This allows you to send multiple requests concurrently and handle responses asynchronously. By using multi-cURL functions, you can avoid blocking the execution of your script while waiting for each request to complete.

// Initialize multi-cURL handle
$mh = curl_multi_init();

// Array to store individual cURL handles
$handles = [];

// URLs for the requests
$urls = [
    'https://api.example.com/endpoint1',
    'https://api.example.com/endpoint2',
    'https://api.example.com/endpoint3'
];

// Create individual cURL handles for each request
foreach ($urls as $url) {
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($mh, $handle);
    $handles[] = $handle;
}

// Execute multi-cURL requests
$running = null;
do {
    curl_multi_exec($mh, $running);
} while ($running > 0);

// Get responses for each request
foreach ($handles as $handle) {
    $response = curl_multi_getcontent($handle);
    // Process the response as needed
    echo $response;
    
    // Remove handle from the multi-cURL handle
    curl_multi_remove_handle($mh, $handle);
    curl_close($handle);
}

// Close multi-cURL handle
curl_multi_close($mh);