file_get_contents函数不能使用的解决方法

来源:互联网 发布:淘宝中评怎么改差评 编辑:程序博客网 时间:2024/05/17 04:27

有些主机服务商把php的allow_url_fopen选项是关闭了,就是没法直接使用file_get_contents来获取远程web页面的内容(采集和小偷程序常用)。那就是可以使用另外一个函数curl。

下面是file_get_contents和curl两个函数同样功能的不同写法

file_get_contents函数的使用示例: 

PHP代码
  1. < ?php    
  2. $file_contents = file_get_contents('http://www.helloks.com/');    
  3. echo $file_contents;    
  4. ?>  


换成curl函数的使用示例: 

PHP代码
  1. < ?php    
  2. $ch = curl_init();    
  3. $timeout = 5;    
  4. curl_setopt ($ch, CURLOPT_URL, 'http://www.helloks.com');    
  5. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);    
  6. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);    
  7. $file_contents = curl_exec($ch);    
  8. curl_close($ch);    
  9.      
  10. echo $file_contents;    
  11. ?>  


利用function_exists函数来判断php是否支持一个函数可以轻松写出下面函数

PHP代码
  1. < ?php    
  2. function vita_get_url_content($url) {    
  3. if(function_exists('file_get_contents')) {    
  4. $file_contents = file_get_contents($url);    
  5. else {    
  6. $ch = curl_init();    
  7. $timeout = 5;    
  8. curl_setopt ($ch, CURLOPT_URL, $url);    
  9. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);    
  10. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);    
  11. $file_contents = curl_exec($ch);    
  12. curl_close($ch);    
  13. }    
  14. return $file_contents;    
  15. }    
  16. ?>  


其实上面的这个函数还有待商榷,如果你的主机服务商把file_get_contents和curl都关闭了,上面的函数就会出现错误。

原创粉丝点击