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

new9mtju  于 2023-02-23  发布在  PHP
关注(0)|答案(1)|浏览(105)

我有一个自定义的cURL函数,必须从远程服务器下载大量的图像。我被禁止了几次之前,当我使用file_get_contents().我发现curl_multi_init()是一个更好的选择,因为它可以一次下载例如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.我需要动态更改文件名
1.在我的函数中,我还检查了远程图像的几个方面。在示例函数中,我只检查大小,并在必要时调整大小,但这个函数完成了更多的事情(我缩短了那部分,但我也使用该函数传递更多的变量。)
应该如何更改代码,以便在LOOP期间只连接到远程服务器一次?
先谢了

q8l4jmvw

q8l4jmvw1#

尝试这种模式的多 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);

相关问题