我无法按照我想要的方式运行php $ _SESSION变量。我有两个文件。第一个设置变量:
<?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>
这两个文件都是通过JavaScript的AJAX调用访问的。
文件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的网络检查器中,我可以看到这两个文件都返回了会话Cookie ID,但它们具有不同的值。查看截图。
更新#3:我已经研究过,发现使用PhoneGap时,php会话是不可能的,即使我是通过jQuery AJAX请求php文件。有人能证实吗?
答案 0 :(得分:0)
确保您还在进行AJAX调用的页面上启动会话session_start();
修改强>
一个不太优选但可能有用的方法是发送带有每个ajax请求的session_id,使其更像是一个令牌。
第一个PHP脚本:
session_start();
echo json_encode([
'message' => 'Session started',
'session_id' => session_id()
]);
exit();
将收到的ID存储在javascript变量中:
var session_id;
$.ajax({
...
success: function(data) {
session_id = data.session_id;
}
...
}
之后发送session_id以及每个AJAX请求:
var data = {session_id: session_id, ... };
$.ajax({
type: "POST",
url: "server.php",
data: data,
success: function(data) {
}
});
您可以生成随机令牌,而不是session_id,以便与每个请求一起发送。