非凡居

PHP Curl请求超时处理办法

PHP Curl请求超时处理办法与代码

写了一个IP管理的工具,增加了api请求的工具,某些接口请求时间比较长,某些接口时间必须要短,希望超过超时时间的请求返回其它的状态码,要跟失败或者curl失败区分开,本质上虽然都是curl失败但是从需求角度要区分开,但是php的curl没有类似事件的一些操作

$curl = curl_init($url);
curl_setopt ( $curl, CURLOPT_POST, 1 );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $curl, CURLOPT_POSTFIELDS, $class->getPostParam() );
curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ( $curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);
if($response === false){
	if(curl_errno($curl) == CURLE_OPERATION_TIMEDOUT){
		//超时的处理代码
	}
}


/*方法二*/
$res = curl_exec($ch); 
  if ($no = curl_errno($ch)) {
   curl_close($ch); //$no错误码7为连接不上,28为连接上了但请求返回结果超时 
    if(in_array(intval($no), [7, 28], true)) {
     return false;// 或者抛出异常自行捕获
     throw new Exception("请求超时"); 
    }
   }
curl_close($ch);