What is correct example (up-to-date approach) use CURL-MULTI? I use the below code, but many times, it fails to get the content (returns empty result, and neither I have experience how to retrieve the correct repsonse/error):
public function multi_curl($urls)
{
$AllResults =[];
$mch = curl_multi_init();
$handlesArray=[];
$curl_conn_timeout= 3 *60; //max 3 minutes
$curl_max_timeout = 30*60; //max 30 minutes
foreach ($urls as $key=> $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
// timeouts: https://thisinterestsme.com/php-setting-curl-timeout/ and https://stackoverflow.com/a/15982505/2377343
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_conn_timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $curl_max_timeout);
if (defined('CURLOPT_TCP_FASTOPEN')) curl_setopt($ch, CURLOPT_TCP_FASTOPEN, 1);
curl_setopt($ch, CURLOPT_ENCODING, ""); // empty to autodetect | gzip,deflate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
$handlesArray[$key] = $ch;
curl_multi_add_handle($mch, $handlesArray[$key]);
}
// other approaches are deprecated ! https://stackoverflow.com/questions/58971677/
do {
$execReturnValue = curl_multi_exec($mch, $runningHandlesAmount);
usleep(100); // stop 100 microseconds to avoid infinity speed recursion
} while ($runningHandlesAmount>0);
//exec now
foreach($urls as $key => $url)
{
$AllResults[$key]['url'] =$url;
$handle = $handlesArray[$key];
// Check for errors
$curlError = curl_error($handle);
if ($curlError!="")
{
$AllResults[$key]['error'] =$curlError;
$AllResults[$key]['response'] =false;
}
else {
$AllResults[$key]['error'] =false;
$AllResults[$key]['response'] =curl_multi_getcontent($handle);
}
curl_multi_remove_handle($mch, $handle); curl_close($handle);
}
curl_multi_close($mch);
return $AllResults;
}
and executing:
$urls = [ 'https://baconipsum.com/api/?type=meat-and-filler',
'https://baconipsum.com/api/?type=all-meat¶s=2'];
$results = $helpers->multi_curl($urls);
Is there something, that can be changed, to have better results?
update: I've found this repository also mentions the lack of documentation about the best-use-case for multi-curl
and provides their approach. However, I ask this on SO to get other competent answers too.