`
alfred_long
  • 浏览: 561096 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

file_get_contents 注意及使用curl替换

阅读更多

使用简单便捷的 file_get_contents("http://example.com/") 函数,来获取一个 URL 的返回内容,但是,如果 http://example.com/ 这个网站响应缓慢,file_get_contents() 就会一直卡在那儿,不会超时。PHP 脚本会一直执行下去。这样,当所有的 php-cgi 进程都卡在 file_get_contents() 函数时,这台 Nginx+PHP 的 WebServer 已经无法再处理新的 PHP 请求了,Nginx 将给用户返回“502 Bad Gateway”。

所以,要做到彻底解决,只能改掉直接使用 file_get_contents("http://example.com/") 的习惯,而是稍微修改一下,加个超时时间,用以下方式来实现 HTTP GET 请求。要是觉得麻烦,可以自行将以下代码封装成一个函数。

 

 

<?php  
$ctx = stream_context_create(array(  
   'http' => array(  
       'timeout' => 1 //设置一个超时时间,单位为秒  
       )  
   )  
);  
file_get_contents("http://example.com/", 0, $ctx);  
?>  

   备注:有时候这个超时时间不起作用,还是用curl函数来获取更好,file_get_contents 获取本地文件可能相对好些。

curl 函数简单获取内容:

    public function curls($url, $timeout = '10')
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项,包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics