我無法讓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頁面? –