dounabi6295 2014-05-28 21:24
浏览 106
已采纳

使用file_get_contents()进行的HTTP请求共享相同的会话数据?

I've got a problem...

I've a MVC-like framework and the redirect mechanism allows me too get snippets of HTML code generated by PHP on a remote host.

I'm getting these snippets by using the file_get_contents() function, with allow_url_fopen turned on.

The problem is the fact I use session data inside these code fragments and the session data is being lost every time. I'm assuming this new request is not sharing the same session data and therefore I need a way to get these fragments without losing my session data.

Any suggestions?

  • 写回答

2条回答 默认 最新

  • doufei9805 2014-05-28 21:50
    关注

    If the files your accessing are on the same server as the calling file then you might as well use include(); like @user574632's answer.

    But if not, to keep the session you will need to handle the cookies the server sends;

    Sessions are cookie based, server sets the session cookie your browser picks it up and uses it for all subsequent requests.

    By default file_get_contents wont handle cookies, so your need to grab the header from the server by accessing $http_response_header array and then match with regex the Set-Cookie: header then store that and on following requests use the cookie and create a stream context with the cookie added to the header and pass that to fgc:

    <?php 
    function get_cookies() {
        //check cookies folder - or make it
        if(!file_exists('./cookies/')){
            mkdir('./cookies/', 0755, true);
        }
        $return = null;
        foreach(glob("./cookies/*.txt") as $file) {
            $return .= file_get_contents($file).';';
        }
        return $return;
    }
    
    function save_cookies($http_response_header) {
        print_r($http_response_header);
        foreach($http_response_header as $header) {
            if(substr($header, 0, 10) == 'Set-Cookie'){
                if(preg_match('@Set-Cookie: (([^=]+)=[^;]+)@i', $header, $matches)) {
                    $fp = fopen('./cookies/'.$matches[2].'.txt', 'w');
                    fwrite($fp, $matches[1]);
                    fclose($fp);
                }
            }
        }
    }
    
    $opts = array('http' =>
        array('header'=>'Cookie: '.get_cookies()."
    ")
    );
    
    $context  = stream_context_create($opts);
    $contents = file_get_contents('http://mywebsite.com/snippets/', false, $context);
    save_cookies($http_response_header);
    
    echo $contents;
    ?> 
    

    Alternatively you should use curl instead its faster and handles cookies fine.

    So something like the following, use curl and then revert to fgc if curl is not present, all wrapped up with cookie support in a class, so the 3 functions are contained:

    <?php
    //example usage
    echo new curl_get_contents('http://example.com/page_that_needs_sessions');
    
    class curl_get_contents{
        public $result;
    
        function __construct($url){
            $this->curl_rev_fgc($url);
        }
    
        function __toString(){
            return $this->result;
        }
    
        private function get_cookies() {
            $return = null;
    
            foreach(glob("./cookies/*.txt") as $file) {
                $return .= file_get_contents($file).';';
            }
            return $return;
        }
    
        private function save_cookies($http_response_header) {
            foreach($http_response_header as $header) {
                if(substr($header, 0, 10) == 'Set-Cookie'){
                    if(preg_match('@Set-Cookie: (([^=]+)=[^;]+)@i', $header, $matches)) {
                        $fp = fopen('./'.$matches[2].'.txt', 'w');
                        fwrite($fp, $matches[1]);
                        fclose($fp);
                    }
                }
            }
        }
    
        private function curl_rev_fgc($url){
            //check cookies folder - or make it
            if(!file_exists('./cookies')){
                mkdir('./cookies/', 0755, true);
            }
    
            $usragent = 'Mozilla/5.0 (compatible; Yourbot/0.1; +https://yoursite/bot.html)';
    
            //Check curl is installed or revert to file_get_contents()
            $curl = function_exists('curl_init') ? true : false;
    
            if($curl){
                $opts = array(
                'http' => array(
                'method' => "GET",
                'header' => 'Cookie: '.$this->get_cookies().'
    ', // cookie in fgc support
                'user_agent' => $usragent)
                );
                $context = stream_context_create($opts);
                $result  = @file_get_contents($url, false, $context);
                $this->save_cookies($http_response_header);
    
                if(empty($result)){
                    $this->result = 'Error fetching: '.htmlentities($url);
                }else{
                    $this->result = $result;
                }
                return;
            }
    
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_TIMEOUT, 60);
            curl_setopt($curl, CURLOPT_USERAGENT, $usragent);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            if(!file_exists('./cookies/curl.txt')){
                file_put_contents('./cookies/curl.txt',null);
            }
            curl_setopt($curl, CURLOPT_COOKIEFILE, './cookies/curl.txt');
            curl_setopt($curl, CURLOPT_COOKIEJAR,  './cookies/curl.txt');
    
            $result = curl_exec($curl);
            if(empty($result)){
                $this->result = 'Error fetching: '.htmlentities($url);
            }else{
                $this->result = $result;
            }
            curl_close($curl);
    
            return;
        }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?