【发布时间】: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