多线程图像下载与cURL, PHP



我正在尝试使用cURL从具有多个连接的URL下载图像,以加快此过程。

下面是我的代码:

function multiRequest($data, $options = array()) {
// array of curl handles
$curly = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $id => $d) {
    $path = 'image_'.$id.'.png';
    if(file_exists($path)) { unlink($path); }
    $fp = fopen($path, 'x');
    $url = $d;
    $curly[$id] = curl_init($url);
    curl_setopt($curly[$id], CURLOPT_HEADER, 0);
    curl_setopt($curly[$id], CURLOPT_FILE, $fp);
    fclose($fp);
    curl_multi_add_handle($mh, $curly[$id]);
}
// execute the handles
$running = null;
do {
    curl_multi_exec($mh, $running);
} while($running > 0);

// get content and remove handles
foreach($curly as $id => $c) {
    curl_multi_remove_handle($mh, $c);
}
// all done
curl_multi_close($mh);
}
执行:

$data = array(
    'http://example.com/img1.png',
    'http://example.com/img2.png',
    'http://example.com/img3.png'
);
$r = multiRequest($data);

所以它没有真正起作用。它创建了3个文件,但是没有字节(空),并且给了我以下错误(3次),并且它正在打印原始。png的某种内容:

Warning: curl_multi_exec(): CURLOPT_FILE resource has gone away, resetting to default in /Applications/MAMP/htdocs/test.php on line 34

所以,你能告诉我怎么做吗?

提前感谢您的帮助!

你正在做的是创建一个文件句柄,然后在循环结束之前关闭它。这将导致curl没有任何文件可写。试试这样做:

//$fp = fopen($path, 'x'); Remove
$url = $d;
$curly[$id] = curl_init($url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_FILE, fopen($path, 'x'));
//fclose($fp); Remove

最新更新