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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题