- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
- curl_setopt($ch, CURLOPT_TIMEOUT, 1);
CURLOPT_CONNECTTIMEOUT 是从请求开始到响应总共等待的时间,
CURLOPT_TIMEOUT是响应等待的时间,后面的数字是等待的秒数(单位秒)
也可以设置毫秒:
- CURLOPT_CONNECTTIMEOUT_MS
- CURLOPT_TIMEOUT_MS
因为在请求第三方接口时发现, 如果只设置了 CURLOPT_TIMEOUT 还是不可避免的会出现延时和卡顿的情况, 遂设置了 CURLOPT_CONNECTTIMEOUT, CURLOPT_CONNECTTIMEOUT 是完全控制在请求方的,只要指定时间没返回数据,就主动断开,不会被延时数据影响到
完整代码
curlPost('http://www.richerdyoung.com',[]);
function curlPost($url , $data=[]){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 20);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 20);
// POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
return $output;
}
评论 (0)