使用cURL,PHP进行多线程图像下载

时间:2013-03-10 21:30:53

标签: 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 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

所以,请你告诉我如何解决这个问题?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您正在做的是创建一个文件句柄,然后在循环结束之前关闭它。这将导致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