使用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?

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;
    }
}
?>

Use include instead. If you need to read the output into a variable to display later/elsewhere in the code, as suggested in the comments, use the output buffer:

ob_start();
include('path/to/file.php');

$included = ob_get_clean();

//nothing has been output to the browser yet

//later on

echo $included;