Introduction
In PHP, cURL (Client URL Library) is commonly used to send HTTP requests and interact with APIs. However, when dealing with multiple requests, making them sequentially can be slow. Multi cURL (cURL Multi) allows us to send multiple requests simultaneously, improving performance and efficiency.
In this blog, we’ll explore how to use Multi cURL in PHP with examples and best practices.
Why Use Multi cURL?
- Speed: Handles multiple requests in parallel, reducing wait times.
- Efficiency: Instead of waiting for each request to complete, all requests run simultaneously.
- Better Performance: Ideal for API-heavy applications.
Basic cURL vs Multi cURL
Single cURL Example
$url = "https://jsonplaceholder.typicode.com/posts/1";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
This approach works fine for a single request but is inefficient when multiple requests are needed.
Using Multi cURL in PHP
Step 1: Initialize Multi cURL
$multiCurl = curl_multi_init();
Step 2: Prepare Multiple Requests
$urls = [
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2",
"https://jsonplaceholder.typicode.com/posts/3"
];
$curlHandles = [];
foreach ($urls as $i => $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($multiCurl, $ch);
$curlHandles[$i] = $ch;
}
Step 3: Execute Multi cURL Requests
do {
$status = curl_multi_exec($multiCurl, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);
Step 4: Fetch Responses
$responses = [];
foreach ($curlHandles as $i => $ch) {
$responses[$i] = curl_multi_getcontent($ch);
curl_multi_remove_handle($multiCurl, $ch);
curl_close($ch);
}
curl_multi_close($multiCurl);
print_r($responses);
Best Practices
- Limit Requests: Avoid too many parallel requests to prevent server overload.
- Handle Errors: Check for HTTP errors using
curl_getinfo($ch, CURLINFO_HTTP_CODE)
. - Use Asynchronous Jobs: If dealing with heavy API calls, consider job queues.
Conclusion
Multi cURL in PHP is a powerful technique for handling multiple HTTP requests in parallel. It significantly improves performance for applications that rely on multiple API calls. By following best practices and using the techniques outlined above, you can optimize your web applications efficiently.