如何在请求或停止运行php脚本时停止卷曲?

时间:2010-03-26 10:20:12

标签: php apache curl

我使用url请求远程网址,有时可能会非常慢或只是关闭。 在这种情况下,我的php脚本仍然在等待响应,它使得apache有许多请求留在内存然后重载。 我需要一种方法来停止curl请求或停止运行PHP脚本时指定的时间过去。 我试过declare(),它对卷曲没有意义。 有人知道如何解决它吗?

BTW:CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT的影响是什么?

以下是代码示例:

function http($url, $method, $postfields = NULL) {
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ci, CURLOPT_TIMEOUT, 5);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, 0);

    switch ($method) {
    case 'POST':
        curl_setopt($ci, CURLOPT_POST, TRUE);
        if (!empty($postfields)) {
            curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
        }
        break;
    case 'DELETE':
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
        if (!empty($postfields)) {
            $url = "{$url}?{$postfields}";
        }
    }

    curl_setopt($ci, CURLOPT_URL, $url);
    $response = curl_exec($ci);
    $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    $this->last_api_call = $url;
    curl_close ($ci);
    return $response;
}

我将connecttimeout和timeout设置为5s,但它没有工作。 Curl仍然花费很长时间来完成请求,但是如果没有响应5秒,这意味着它已经关闭或网络状况不好,应该停止它。

1 个答案:

答案 0 :(得分:1)

如果在指定时间后仍未建立连接,CURLOPT_CONNECTTIMEOUT将停止请求

如果在指定时间后仍未收到完整回复,CURLOPT_TIMEOUT将停止请求

对我来说,我有时候会遇到问题但仍然没有超时,在这种情况下你可以尝试这样的事情:

declare(ticks = 1);

function sig_handler($sig) {

 mysql_query("insert into log (event) values ('Timed out!')");
 die("Timed out!");

}

pcntl_signal(SIGALRM,"sig_handler");
// call sig_handler function after 30 seconds
pcntl_alarm(30);

// curl code here
相关问题