当我需要传递自定义选项时,如何使用PHP curl_multi_init()用法



我有一个自定义的cURL函数,它必须从远程服务器下载大量图像。我以前使用file_get_contents((时被禁止过几次。我发现curl_multi_init((是更好的选择,因为有了1个连接,它可以一次下载20个图像。我制作了一个使用curl_init((的自定义函数,我正试图弄清楚如何实现curl_multi_init((,所以在我的LOOP中,我从数据库中获取了20个URL的列表,我可以调用我的自定义函数并在最后一个循环中使用curl_close((。在当前情况下,我的函数为LOOP中的每个url生成连接。以下是功能:

function downloadUrlToFile($remoteurl,$newfileName){
$errors = 0;
$options = array(
CURLOPT_FILE    => fopen('../images/products/'.$newfileName, 'w'),
CURLOPT_TIMEOUT =>  28800,
CURLOPT_URL     => $remoteurl,
CURLOPT_RETURNTRANSFER => 1
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$imageString =curl_exec($ch);
$image = imagecreatefromstring($imageString);
if($imageString !== false AND !empty($imageString)){
if ($image !== false){
$width_orig = imagesx($image);
if($width_orig > 1000){
$saveimage = copy_and_resize_remote_image_product($image,$newfileName);
}else $saveimage = file_put_contents('../images/products/'.$newfileName,$imageString);

}else $errors++;
}else $errors++;
curl_close($ch);
return $errors;
}

必须有一种方法来使用curl_multi_init((和我的函数downloadUrlToFile,因为:

  1. 我需要随时更改文件名
  2. 在我的功能中,我还检查了一些远程图像。。在示例函数中,我只检查大小,必要时调整大小,但这个函数做的事情要多得多(我缩短了那个部分,但我也使用这个函数传递更多的变量。(

应该如何更改代码,以便在LOOP期间只连接到远程服务器一次?

提前感谢

尝试多CURL 的此模式

$urls = array($url_1, $url_2, $url_3);
$content = array();
$ch = array();
$mh = curl_multi_init();
foreach( $urls as $index => $url ) {
$ch[$index] = curl_init();
curl_setopt($ch[$index], CURLOPT_URL, $url);
curl_setopt($ch[$index], CURLOPT_HEADER, 0);
curl_setopt($ch[$index], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch[$index]);
}
$active = null;
for(;;) {
curl_multi_exec($mh, $active);
if($active < 1){
// all downloads completed
break;
}else{
// sleep-wait for more data to arrive on socket.
// (without this, we would be wasting 100% cpu of 1 core while downloading,
// with this, we'll be using like 1-2% cpu of 1 core instead.)
curl_multi_select($mh, 1);
}
}
foreach ( $ch AS $index => $c ) {
$content[$index] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
//You can add some functions here and use $content[$index]
}
curl_multi_close($mh);

最新更新