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

时间:2014-05-28 21:24:41

标签: php session file-get-contents

我遇到了问题...

我是一个类似MVC的框架,重定向机制让我也可以在远程主机上获得PHP生成的HTML代码片段。

我通过使用file_get_contents()函数获取这些代码段,并启用了allow_url_fopen。

问题在于我在这些代码片段中使用会话数据,并且会话数据每次都丢失。我假设这个新请求没有共享相同的会话数据,因此我需要一种方法来获取这些片段而不会丢失我的会话数据。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

如果您访问的文件与调用文件位于同一服务器上,那么您也可以使用@ {user = @74562的答案等include();

但如果没有,为了保持会话,您将需要处理服务器发送的cookie;

会话基于cookie,服务器设置您的浏览器选择的会话cookie,并将其用于所有后续请求。

默认情况下file_get_contents不会处理Cookie,因此您需要通过访问$http_response_header数组从服务器获取标头,然后使用正则表达式匹配Set-Cookie:标头,然后将其存储在以下内容中请求使用cookie并创建一个流上下文,并将cookie添加到头部并将其传递给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()."\r\n")
);

$context  = stream_context_create($opts);
$contents = file_get_contents('http://mywebsite.com/snippets/', false, $context);
save_cookies($http_response_header);

echo $contents;
?> 

或者你应该使用curl而不是更快,并处理好饼干。

如下所示,使用curl然后如果curl不存在则恢复为fgc,所有包含在类中的cookie支持,因此包含3个函数:

<?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().'\r\n', // 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 :(得分:0)

使用include代替。如果您需要将输出读入变量以便稍后/代码中的其他位置显示,请按照注释中的建议使用输出缓冲区:

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

$included = ob_get_clean();

//nothing has been output to the browser yet

//later on

echo $included;