PHP CURL
now can be used within Swoole Coroutine, you can run multiple CURL
requests concurrently within a single process within multiple coroutines.
To enable coroutine support for PHP CURL
, you have to enable the Coroutine Hook for CURL:
<?php
Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_CURL);
In the nutshell, PHP CURL
is replaced with Coroutine HTTP Client API implementation if you have enabled SWOOLE_HOOK_CURL
, otherwise you are using the original blocking PHP CURL
which should not be used within the Coroutine context.
Example:
<?php
// enable coroutine support for PHP CURL
Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_CURL);
Co\run(function() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$headers = array();
$headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
if ($output === FALSE) {
echo "CURL Error:". curl_error($ch). " ". $url. "\n";
return $resp;
}
curl_close($ch);
});
Check PHP Coroutine about how to execute multiple coroutines concurrently.