比file_get_contents稳定的curl_get_contents分享
作者:bea
分享一个实际在用的函数: 代码如下: /*比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_RETUR
分享一个实际在用的函数:
代码如下:
/*比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('http://');
相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致PHP进程占用CPU达100%,因此这个函数就诞生了。
curl的一些常识介绍
保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。
另来自张宴的file_get_contnets的优化,具体可看:
http:///article/28030.htm
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
代码如下:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //设置一个超时时间,单位为秒
)
)
);
file_get_contents("http:///", 0, $ctx);
另外,据不完全测试,使用curl获取页面比用file_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('http://');
相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致PHP进程占用CPU达100%,因此这个函数就诞生了。
curl的一些常识介绍
保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。
另来自张宴的file_get_contnets的优化,具体可看:
http:///article/28030.htm
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
代码如下:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //设置一个超时时间,单位为秒
)
)
);
file_get_contents("http:///", 0, $ctx);
另外,据不完全测试,使用curl获取页面比用file_get_contents稳定的多。
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- php木马webshell扫描器代码
- php addslashes及其他清除空格的方法是不安全的
- PHP中创建空文件的代码[file_put_contents vs touch]
- PHP取进制余数函数代码
- 用phpmailer实现简单openvpn用户认证的实现代码
- PHP采集腾讯微博的实现代码
- Php图像处理类代码分享
- php中可能用来加密字符串的函数[base64_encode、urlencode、sha1]
- php 阴历-农历-转换类代码
- yii框架中的Url生产问题小结
- fgetcvs在linux的问题
- PHP异步调用socket实现代码
- 114啦源码(114la)不能生成地方房产和地方报刊问题4级页面0字节的解决方法
- PHP警告Cannot use a scalar value as an array的解决方法
- Trying to clone an uncloneable object of class Imagic的解决方法
- win2003服务器使用WPS的COM组件的一些问题解决方法
- php通过COM类调用组件的实现代码
- 关于IIS php调用com组件的权限问题
- Uncaught exception com_exception with message Failed to create COM object