使用cURL的多线程图像下载,PHP
我正在尝试使用cURL从一个具有多个连接的URL下载图像,以加快这个过程 这是我的密码:使用cURL的多线程图像下载,PHP,php,image,curl,download,Php,Image,Curl,Download,我正在尝试使用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
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次),它正在打印原始.PNGs的某些内容:
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
在哪里打开文件&write&close?它作为setopt调用的一部分打开。通常,资源在脚本结束时关闭,但是如果需要关闭它,可以将资源分配给数组,并在执行curl后关闭它们。帮助:谢谢:)我可以执行
curl\u multi\u remove\u handle旁边的fclose
!再次感谢!