php curl卡顿缓慢的问题

这是多个原因造成的,

一是,php运行缓慢,最好重启一下。

如果重启还是不能解决,

1、DNS解析慢的原因,

处理方案,使用gethostbyname代替

推荐代码如下:

$url_arr = parse_url($full_url);
$url_host = $url_arr["host"];
$url_port = $url_arr["port"];
$url_ip = gethostbyname($url_host);
if($url_host==$url_ip){
	$url_ip='127.0.0.1';
}
$url_nameresolve="{$url_host}:{$url_port}:{$url_ip}";
curl_setopt($ch, CURLOPT_RESOLVE, [$url_nameresolve]);
//$url = preg_replace("#^http([s]?)://$host#", "http\$1://$ip", $url);
//curl_setopt($curl, CURLOPT_HTTPHEADER, "Host: $host");

或者尝试添加一个禁用ipv6解析

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

处理完毕,速度上来了。

其它方法,需要shell_exec扩展,不太推荐

function gethostbyname2($host, $timeout = 3) {
$query = 'nslookup -timeout='.$timeout.' -retry=1 '.$host;
$query = shell_exec($query);
if(preg_match('/\nAddress: (.*)\n/', $query, $matches))
return trim($matches[1]);
return $host;
}

2、当POST内容超过1024时,加入如此header声明,否则504错误

$header[] = "Expect:";
if ($header) {
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}

3、使用旧版本协议,原因暂时不明

curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

记录完毕。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注