我正試圖想出一個會話超時(第一次)。當我調用if語句時,它將獲得$ _SESSION變量的空值。我將會話從頂部的header.php文件中開始。當它在用戶登錄創建與此代碼會話:PHP會話將返回null
public static function create_session($values) {
foreach ($values as $key => $value) {
if ($key != "password") {
$_SESSION[$key] = $value;
}
}
$_SESSION["timestamp"] = time();
}
然後重定向到一個索引頁至極只包含:
<?php
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
這個工作,它打印頁面上的所有會話變量正好。
這是用index.php文件打印出來的代碼。
Array
(
[id] => 33
[first_name] => removed to not show name
[last_name] => removed to not show name
[email] => [email protected]
[timestamp] => 1437486426
)
在我的footer.php文件中,我有一些jquery每5秒運行一次定時函數,調用timeout.php文件。
(function poll() {
setTimeout(function() {
$.ajax({ url: "timeout.php", success: function(data) {
console.log(data);
}, dataType: "json", complete: poll });
}, 5000);
})();
超時PHP文件只有這個代碼是:
if (isset($_SESSION)) {
if ($_SESSION['timestamp'] + 10 * 60 < time()) {
// session timed out
echo json_encode(array('session' => $_SESSION, 'session_timestamp' => $_SESSION['timestamp'], 'timestamp_calculation' => $_SESSION['timestamp'] + 10 * 60, 'timeoutstatus' => 'timed out'));
} else {
// session ok
echo json_encode(array('session' => $_SESSION, 'session_timestamp' => $_SESSION['timestamp'], 'timestamp_calculation' => $_SESSION['timestamp'] + 10 * 60, 'timeoutstatus' => 'not timed out'));
}
} else {
echo json_encode(array('session' => 'Session does not exits'));
}
出於某種原因,我收到會話不存在。如果我刪除if語句的那部分,並且只測試超時,所有調用$ _SESSION的json數組變量都會返回null。我不知道這是爲什麼。我感謝您的幫助。
作爲對此的重複。最初的想法是,session_start()沒有被調用。我曾經提到它在第一段中被調用,它在所有其他的PHP代碼之前。我也確認我可以在索引頁面中調用$ _SESSION變量。當我試圖通過從我的footer.php調用的ajax函數來讀取它時,我只會遇到問題。
我沒有看到'在session_start()'任何地方。我沒有看到你的索引頁如何工作,就像你說的那樣。 –
你開始會議嗎?在session_start(); http://php.net/session_start – Webice
session_start()函數位於header.php文件中,因此無論如何都會調用它。我沒有在這裏的代碼中包含它。所以heirarchy去header.php與session_start() - > index.php - > footer.php – user2112618