curl_multi_select的无穷循环

时间:2019-06-17 17:10:27

标签: php curl

我正在尝试通过运行以下curl_multi替换file_get_contents来加快执行速度较慢的脚本的速度:

//for example only
$vcards = array($id1=>$vcardstring1, $id2=>$vcardstring2, /* ... */);

function sendVcards(array $vcards, callable $f){
    //debug_message is a custom function defined elsewhere to print data and flush output for debugging
    //debug_message("Sending vcards");

    $multi = curl_multi_init();
    $reqs  = array();

    global $settings;

    foreach ($vcards as $id => $vcard_data) {
        //url for example only
        $url = "https://example.com/address-book/guid-123456.ics";
        $req = curl_init();
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_CUSTOMREQUEST => 'PUT',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode("username" . ':' . "userpass"),
                'Content-Length: '.strlen($vcard_data),
            ),
            CURLOPT_POSTFIELDS => $vcard_data,
            CURLINFO_HEADER_OUT => true,
        );
        curl_setopt_array($req, $options);
        //debug_message("Set curl options");
        curl_setopt($req, CURLOPT_HEADER, 0);
        curl_multi_add_handle($multi, $req);
        $reqs[$id] = $req;
    }

    // While we're still active, execute curl
    $active = null;

    // Execute the handles
    do {
        $mrc = curl_multi_exec($multi, $active);
        //debug_message("Executed CURL 1");
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($multi) != -1) {
            do {
                $mrc = curl_multi_exec($multi, $active);
                //debug_message("Executed CURL 2");
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        } else {
            //debug_message("Not Executing CURL 2",$multi);
        }
    }


    //debug_message("Closing curl handles");
    // Close the handles
    foreach ($reqs as $id => $req) {
        $result = curl_multi_getcontent($req);

        //debug_message("vcard sent for ".$id);

        if(preg_match('/"([0-9-]+)"/',current(array_filter(curl_getinfo($req, CURLINFO_HEADER_OUT), function($var){ return preg_match("/\bETag\b/i", $var); })),$ETag)){
            $ETag = $ETag[1];
        } else {
            $ETag = "";
        }

        //debug_message("etag received: ".$ETag);

        $f($id,$ETag);
        curl_multi_remove_handle($multi, $req);
    }
    curl_multi_close($multi);
}

我遇到的问题是脚本进入了一个无限循环,因为if (curl_multi_select($multi) != -1)从不等于true。

我是否在上面的脚本的curl过程中缺少某些内容,或者是接收服务器出现故障?在使用file_get_contents使用相同的授权字符串和相同的url之前,它似乎可以正常工作,因此我不认为问题出在URL或授权部分。

我为这个广泛的问题表示歉意,但是我对curl_multi_select并不那么熟悉,我尽力阅读了php库:https://www.php.net/manual/en/function.curl-multi-select.php,但我自己却无处解决。

0 个答案:

没有答案