我无法让php $ _SESSION变量以我想要的方式工作。我有两个文件。第一个设置变量:第二个php文件找不到会话在第一个文件中开始
<?php
session_start();
header("Access-Control-Allow-Origin: *");
$_SESSION['authenticated'] = "yes";
echo json_encode('Authenticated successfully.');
?>
,第二个试图找回它:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
print '<pre>';
var_dump($_SESSION['authenticated']);
print '</pre>';
?>
但第二个文件始终打印NULL
当它应该打印"Yes"
和一个新的错误记录在服务器的日志:
[Thu Sep 22 12:52:47.763114 2016] [:error] [pid 26644] [client <ip_here>] PHP Notice: Undefined index: authenticated in <Second_file> on line 5, referer: <client_url_here>
这两个文件都通过AJAX访问从JavaScript调用。
文件1件作品Ajax代码如下:
$.ajax({
url: corrDomain + '/auth.php', //Path and name of file #1. It's correct and working.
type: 'POST',
data: {
//This part is excluded in the above php code for simplification. It's guaranteed to work.
username: username,
password: password,
action: 'init'
},
dataType: 'json',
success: function(data){
//Check if data contains the right information, then call function for file #2.
},
error: function(){
//Something went wrong
}
});
当该代码得到竖起大拇指从PHP,该用户被授权下面的代码将文件#2上运行:
$.ajax({
url: path + '/getProducts.php', //Also correct and working.
type: 'POST',
dataType: 'json',
success: function(data){
products.push(data);
orderProductIds();
//Update col 1 + 2;
updateOrders('reload');
//Set interval of updating col 1.
setInterval(function(){
updateOrders('update');
}, 10000);
},
error: function(){
alert('Something went wrong.');
}
});
更新:我添加session_name();
在我所有的PHP文件的第一行。如果我在浏览器中打开每个文件,会话现在可用,但如果我通过AJAX访问它们,则会话不起作用。所以问题仍然存在,但也许这可以帮助你。
更新#2:在Chrome的网络检查器中,我可以看到两个文件都返回Session Cookie ID,但它们具有不同的值。查看屏幕截图。
更新#3:我研究后发现,PHP会话使用PhoneGap的时候,即使我请求通过jQuery AJAX的PHP文件是不可能的。有人能证实这一点吗?
你确定,你在一个会话中首先访问第一个文件吗? –
这不是我在页面加载时通过AJAX访问的第一个文件,但它是第一个涉及会话的文件。 –
发布您的ajax代码。你是否正确地考虑了ajax中的“a”,或者你有可能在setter之前打到getter页面? –