【问题标题】:PHP file_get_contents doesn't retrieve cookiesPHP file_get_contents 不检索 cookie
【发布时间】:2014-01-21 01:38:56
【问题描述】:

我已经阅读了一些关于这个问题的主题..有些人说要使用 cURL(虽然我不知道如何..)

我有两个文件,index.php 和 response.php。

index.php

/* After the body tag, in the middle of screen */
<?php echo file_get_contents('http://localhost/football/classes/response.php?type=clients'); ?>

此代码运行良好,直到我意识到我需要在页面加载时检索相同的信息,但使用 cookie。

我的旧 response.php 文件是这样的:

switch($_REQUEST['type']){
    case 'clients':
        $content = $load->clients();
        echo $content;
        break;
}

但现在我需要在函数clients() 中执行相同的代码,但需要一个参数。这个参数是一个cookie。

switch($_REQUEST['type']){
    case 'clients':
        $display = 0;
        if(isset($_COOKIE['display'])){ 
            $display = 1;
        }
        $content = $load->clients($display);
        echo $content;
        break;
}

我总是收到$display = 0;,因为 PHP 没有检测到 cookie。虽然,这个 cookie 是在 Chrome cookie 中初始化的。即使我这样做var_dump($_COOKIE); 我仍然没有收到任何东西。

我知道这个问题是因为file_get_contents()这个问题怎么解决?

谢谢。

编辑:尝试了@Martin 解决方案,但没有成功。 file_get_contents receive cookies

<?php 
    $ckfile = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init ("http://localhost/football/index.php");
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);

    $ch = curl_init ("http://localhost/football/classes/response.php?type=clients");
    curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);

    echo $output;
?>

页面不断循环,并没有停止。它什么也没显示。

【问题讨论】:

  • file_get_contents() 做的正是它应该做的,即获取文件......它不是网络浏览器的替代品,它不支持 cookie 或执行 javascript 或任何其他东西Web 浏览器会这样做....如果您想要这些,请使用 curl(用于 cookie)或无头浏览器工具,例如 phantomjs
  • 为什么需要使用file_get_contents? response.php 实际上是在不同的服务器上吗
  • @user574632 yes..and file_get_contents 是我找到echo 内容的方式。还有其他想法吗?
  • $_SESSION 应该可以工作,更多控制使用 curl

标签: php cookies curl file-get-contents


【解决方案1】:

超级全局$_COOKIE 仅包含您的访问者在请求您的页面时发送到您的 Web 服务器的 cookie,它永远不会包含其他服务器在加载另一个页面时可能发送到您的应用程序的 cookie。

但您仍然可以使用$http_response_header 检索所有响应标头。

PHP 文档中的更多信息:$http_response_header

【讨论】:

  • 它是否也包含 cookie?
  • 这不符合我的需要。
  • @user3065191 您可以简单地遍历数组$http_response_header 并找到以Set-Cookie: 开头的条目。您可以随意将它们添加到$_COOKIE,将它们发送给您的客户等。为什么这不符合您的需求?
  • 我创建了 var_dump()$http_response_header 并没有显示我的 cookie..只有 PHPSESSID,虽然我有更多的 cookie。
猜你喜欢
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多