Reputation: 12814
I have tried many online examples of using curl_multi_exec. Unfortunately none of them "work" for me, as in they block forever and I never get a response.
I tried modifying the some of the examples so that they will sleep if I get a -1 response which has no effect (other than stopping my CPU going to 100%). I tried both in the CLI and running as a webserver with the same result.
Question: Do these scripts work for other people or do they need modifying/updating for PHP 7.0? Perhaps there is a package other than php7.0-curl that I need to install?
I am runing PHP 7.0 on Ubuntu 16.04:
PHP 7.0.18-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.18-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies
Upvotes: 1
Views: 1838
Reputation: 1540
As a comment says at http://php.net/manual/en/function.curl-multi-init.php#115055, there's a problem on the official document. So the class of example 2 should look something like this. Changed the first while loop
class ParallelGet
{
function __construct($urls)
{
// Create get requests for each URL
$mh = curl_multi_init();
foreach($urls as $i => $url)
{
$ch[$i] = curl_init($url);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $ch[$i]);
}
// Start performing the request
do {
$execReturnValue = curl_multi_exec($mh, $runningHandles);
} while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
// Loop and continue processing the request
while ($runningHandles && $execReturnValue == CURLM_OK) {
// !!!!! changed this if and the next do-while !!!!!
if (curl_multi_select($mh) != -1) {
usleep(100);
}
do {
$execReturnValue = curl_multi_exec($mh, $runningHandles);
} while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
}
// Check for any errors
if ($execReturnValue != CURLM_OK) {
trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING);
}
// Extract the content
foreach($urls as $i => $url)
{
// Check for errors
$curlError = curl_error($ch[$i]);
if($curlError == "") {
$res[$i] = curl_multi_getcontent($ch[$i]);
} else {
print "Curl error on handle $i: $curlError\n";
}
// Remove and close the handle
curl_multi_remove_handle($mh, $ch[$i]);
curl_close($ch[$i]);
}
// Clean up the curl_multi handle
curl_multi_close($mh);
// Print the response data
print_r($res);
}
}
Upvotes: 1