Curl multi handle in PHP allows us to execute multiple HTTP requests in parallel, improving performance when dealing with several network operations at once. Instead of waiting for each request to complete sequentially, the multi handle lets us add multiple handles to a single manager, process them simultaneously, and then retrieve their results efficiently. This is especially useful for applications that need to fetch data from multiple APIs or remote resources at the same time.
Since PHP 8.5, we can use the curl_multi_get_handles function for retrieving an array of CurlHandle objects from a CurlMultiHandle. Before this function existed, applications had to keep their own list of CurlHandle objects added to a CurlMultiHandle, often using a WeakMap.
The code demonstrates how to fetch multiple URLs in parallel using a CurlMultiHandle. Each URL gets its own CurlHandle, which is added to the multi handle and executed simultaneously. Since PHP 8.5, we can now use curl_multi_get_handles to retrieve all handles directly, eliminating the need to keep a separate list of CurlHandle objects manually.
<?php
$urls = [
'https://httpbin.org/get?test=1',
'https://httpbin.org/get?test=2',
];
$mh = curl_multi_init();
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
}
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
$handles = curl_multi_get_handles($mh);
foreach ($handles as $ch) {
$content = curl_multi_getcontent($ch);
echo $content;
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
Leave a Comment
Cancel reply