Parallel cURL Request with WRITEFUNCTION Callback

懵懂的女人 提交于 2019-11-30 16:43:29
User4407

I finally got it figured out. The biggest problem was the fact that cURL was ignoring the WRITEFUNCTION until I placed it as the very last option specified, as I posted here: cURL WRITEFUNCTION not Being Called. I actually didn't need the return transfer, since I wrote the output to a class variable. That was necessary because when the callback returns -1, nothing gets returned. The following code works great:

var $full_length = array();
var $result = array();

function get_headers($urls){
    $curly = array();
    $mh = curl_multi_init();
    foreach ($urls as $key => $url) {
        $callback = $this->get_write_function($key);
        $curly[$key] = curl_init
        curl_setopt($curly[$key], CURLOPT_URL,            $url);
        curl_setopt($curly[$key], CURLOPT_HEADER,         0);
        curl_setopt($curly[$key], CURLOPT_WRITEFUNCTION, $callback);
        curl_multi_add_handle($mh, $curly[$key]);
    }
    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while($running > 0);
    foreach($curly as $key => $cnt) {
        curl_multi_remove_handle($mh, $cnt);
    }
    curl_multi_close($mh);
    return $this->result;
}

function get_write_function($key){
    $this->full_length[$key] = 0;
    $this->result[$key] = '';
    $obj = $this;
    $funky = function ($ch, $str) use ($obj, $key){
        $obj->result[$key] .= $str;
        $length = strlen($str);
        $obj->full_length[$key] += $length;
        if($obj->full_length[$key] >= 4000){
            return -1;
        }
        return $length;
    };
    return $funky;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!