Home  >  Article  >  php教程  >  php解决ipv6使curl获取网页内容超时解决办法

php解决ipv6使curl获取网页内容超时解决办法

WBOY
WBOYOriginal
2016-05-25 16:44:131759browse

问题原因:如果开启了IPv6,curl默认会优先解析 IPv6,在对应域名没有 IPv6 的情况下,会等待 IPv6 dns解析失败 timeout 之后才按以前的正常流程去找 IPv4,在程序中我对curl获取内容都作了较为严格的超时限制,所以就会造成无法获取内容的问题.

解决的方法是设置默认访问为ipv4,php的curl设置方法具体如下:

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 
//设置curl默认访问为IPv4 
if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){ 
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 
} 
 
//设置curl请求连接时的最长秒数,如果设置为0,则无限 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
//设置curl总执行动作的最长秒数,如果设置为0,则无限 
curl_setopt ($ch, CURLOPT_TIMEOUT,$timeout*3); 
$file_contents = curl_exec($ch); 
curl_close($ch);

:curl_setopt($ch, CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4) 只有在php版本5.3及以上版本,curl版本7.10.8及以上版本时,以上设置才生效.


本文链接:

收藏随意^^请保留教程地址.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn