thlib / php-curl-multi-basic
PHP curl_multi的基本实现。代码简洁,易于配置,更好的内存管理,无双重循环,无100% CPU占用错误。
1.0.2
2020-04-10 11:31 UTC
Requires
- php: >=5.3.0
This package is auto-updated.
Last update: 2024-09-24 19:49:29 UTC
README
PHP curl multi的基本实现
curl multi有很多实现,但大多数存在CPU使用率高、内存管理不高效、每个请求完成后才运行等问题。
以下是一个避免所有这些问题的示例,而不需要过度加载功能。
require 'CurlMulti.php';
$handles = [
[
// regular url
CURLOPT_URL=>"http://example.com/",
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_WRITEFUNCTION=>function($ch, $body)
{
print $body;
return strlen($body);
}
],
[
// invalid url
CURLOPT_URL=>"httpzzz://example.com/",
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_WRITEFUNCTION=>function($ch, $body)
{
print $body;
return strlen($body);
}
],
[
// url with a redirect
CURLOPT_URL=>"https://php.ac.cn",
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_HEADERFUNCTION=>function($ch, $header)
{
print "header from https://php.ac.cn: ".$header;
return strlen($header);
},
CURLOPT_WRITEFUNCTION=>function($ch, $body)
{
print $body;
return strlen($body);
}
]
];
//create the multiple cURL handle
$CurlMulti = new CurlMulti();
foreach($handles as $opts) {
// create cURL resources
$ch = curl_init();
// set URL and other appropriate options
curl_setopt_array($ch, $opts);
// add the handle
$CurlMulti->add($ch);
}
$statusCode = $CurlMulti->run(function($ch, $statusCode) {
$info = curl_getinfo($ch);
if ($statusCode !== CURLE_OK) {
// handle the error somehow
print "Curl handle error: ".curl_strerror($statusCode)." for ".$info['url'].PHP_EOL;
return;
}
//$body = curl_multi_getcontent($ch);
//print $body;
});
if ($statusCode !== CURLM_OK) {
print "Curl multi handle error: ".curl_multi_strerror($statusCode)." for ".$info['url'].PHP_EOL;
}