【问题标题】:How to make file_get_contents session aware?如何让 file_get_contents 会话感知?
【发布时间】:2016-05-29 07:01:12
【问题描述】:

我有一个 php 脚本,它将在服务器上发出一系列请求。第一个请求将是登录请求。

问题是file_get_contents 似乎每次都会创建一个新会话,那么我怎样才能让它知道会话呢?

这是我需要让它记住会话的函数:

function request($method, $data, $url){
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n"."Cookie: ".session_name()."=".session_id()."\r\n",
            'method'  => $method,
            'content' => http_build_query($data),
        ),
    );

    $context  = stream_context_create($options);
    session_write_close();
    $result = file_get_contents($url, false, $context);

    return $result;
}

【问题讨论】:

  • 应该很明显:通过传递现有会话 id ... // 如果您使用 cURL 代替,这可能会更容易,因为这意味着已经可以跨请求正确处理 cookie。
  • 付出了很多努力。保留并提取 $http_response_header 以使用相应的会话 cookie 重新填充请求 context
  • @mario 但这是一个 html 页面而不是 api
  • 这有什么关系?为什么您的代码假定本地 session_id() 和名称与远程相同?
  • 不,请自己去研究。

标签: php http web backend


【解决方案1】:

我只是使用 curls 而不是 file_get_contents 并且一切正常:

function request_url($method='get', $vars='', $url) {
    $ch = curl_init();
    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt');
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
}

【讨论】:

  • 做得很好。我可以看到这对很多新手都有帮助。感谢您发布您的发现!
  • 有关此答案为何有效的说明,请阅读this post.
【解决方案2】:

Hazem's answer 中解释为什么 cookie 在 cURL 中起作用。

Author:Nate I

奇迹发生在CURLOPT_COOKIEJARCURLOPT_COOKIEFILE

CURLOPT_COOKIEJAR 告诉 cURL 将所有内部已知的 Cookie 写入指定文件。在这种情况下,“cookies/cookies.txt”。对于大多数用户,通常建议使用tempnam('/tmp', 'CURLCOOKIES') 之类的名称,这样您就可以确定可以生成此文件。

CURLOPT_COOKIEFILE 告诉 cURL 在 cURL 请求期间将哪个文件用于 Cookie。这就是为什么我们将它设置为我们刚刚将 Cookie 转储到的同一文件。

【讨论】:

    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2012-03-30
    • 1970-01-01
    • 2016-05-04
    相关资源
    最近更新 更多