Rumah > Artikel > pembangunan bahagian belakang > php curl获取网页内容(IPV6下超时)的解决方法_PHP教程
原因:
如果开启了IPv6,curl默认会优先解析 IPv6,在对应域名没有 IPv6 的情况下,会等待 IPv6 dns解析失败 timeout 之后才按以前的正常流程去找 IPv4。在程序中我对curl获取内容都作了较为严格的超时限制,所以就会造成无法获取内容的问题。
解决方法:设置默认访问为ipv4。
php的curl设置方法如下:
<?<span php </span><span /*</span><span * * IPV6下curl超时问题 * edit by www.jbxue.com </span><span */</span> <span $ch</span> =<span curl_init(); curl_setopt (</span><span $ch</span>, CURLOPT_URL, <span $url</span><span ); curl_setopt (</span><span $ch</span>, CURLOPT_RETURNTRANSFER, <span true</span><span ); </span><span //</span><span 设置curl默认访问为IPv4</span> <span if</span>(<span defined</span>('CURLOPT_IPRESOLVE') && <span defined</span>('CURL_IPRESOLVE_V4'<span )){ curl_setopt(</span><span $ch</span>, CURLOPT_IPRESOLVE,<span CURL_IPRESOLVE_V4); } </span><span //</span><span 设置curl请求连接时的最长秒数,如果设置为0,则无限</span> curl_setopt (<span $ch</span>, CURLOPT_CONNECTTIMEOUT, <span $timeout</span><span ); </span><span //</span><span 设置curl总执行动作的最长秒数,如果设置为0,则无限</span> curl_setopt (<span $ch</span>, CURLOPT_TIMEOUT,<span $timeout</span>*3<span ); </span><span $file_contents</span> = curl_exec(<span $ch</span><span ); curl_close(</span><span $ch</span>);
注:curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4) 只有在php版本5.3及以上版本,curl版本7.10.8及以上版本时,以上设置才生效。