比file_get_contents稳定的curl_get_contents分享
分享一个实际在用的函数:
/*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s。*/
function curl_get_contents($url,$timeout=1) {
$curlhandle = curl_init();
curl_setopt( $curlhandle , curlopt_url, $url );
curl_setopt( $curlhandle , curlopt_returntransfer, 1 );
curl_setopt( $curlhandle , curlopt_timeout, $timeout );
$result = curl_exec( $curlhandle );
curl_close( $curlhandle );
return $result;
}
$hx = curl_get_contents('//www.jb51.net');
相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致php进程占用cpu达100%,因此这个函数就诞生了。
保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。
另来自张宴的file_get_contnets的优化,具体可看:
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //设置一个超时时间,单位为秒
)
)
);
file_get_contents("//www.jb51.net/", 0, $ctx);
另外,据不完全测试,使用curl获取页面比用file_get_contents稳定的多。
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
-
-
闲下来想一想
自从去年系统大升级以来,不但需要维稳新系统,新需求一个接一个。虽然疫情期间,工作不但没有闲下来反而更忙了。不过话...
[阅读全文]
-
-
-
-
-
-
网友评论