2010-03-26 76 views
0

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

顺便说一句: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和超时为5秒,但忽略了最低workd。 Curl仍然花费很长时间才能完成请求,但是如果url在5秒内没有响应,这意味着它已关闭或网络状况不佳,应该停止它。

+1

设置超时是常见的解决方案。 'CURLOPT_TIMEOUT'有什么问题?如果您需要帮助,您可能需要添加一些代码和描述,这些都不起作用。 – 2010-03-26 10:21:34

回答

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 
+0

我无法用pcntl测试,服务器不支持它。非常感谢。 – Chris 2010-03-26 12:29:11