Skip to content
PHP Logo

What is the purpose of using multi_curl for sending requests in PHP?

When sending multiple HTTP requests in PHP, using multi_curl can significantly improve performance by allowing the requests to be sent concurrently, rather than sequentially. This can help reduce the overall execution time of the script by leveraging the parallel processing capabilities of the server.

php
// Initialize multi_curl
$multi_curl = curl_multi_init();

// Create individual curl handles for each request
$curl_handles = [];
foreach ($urls as $url) {
    $curl_handles[] = createCurlHandle($url);
}

// Add all curl handles to multi_curl
foreach ($curl_handles as $handle) {
    curl_multi_add_handle($multi_curl, $handle);
}

// Execute all requests concurrently
$running = null;
do {
    curl_multi_exec($multi_curl, $running);
} while ($running > 0);

// Close all curl handles
foreach ($curl_handles as $handle) {
    curl_multi_remove_handle($multi_curl, $handle);
    curl_close($handle);
}

// Close multi_curl
curl_multi_close($multi_curl);