I am trying to come up with a session timeout (first time). When ever I am calling the if statement it is getting a null for the $_SESSION variable. I have the session start in the header.php file at the top. When the user logs in it creates the session with this code:
public static function create_session($values) {
foreach ( $values as $key => $value ) {
if ($key != "password") {
$_SESSION[$key] = $value;
}
}
$_SESSION["timestamp"] = time();
}
It then redirects to an index page wich only contains:
<?php
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
This works, it prints all the session variables on the page just fine.
This is what prints out in the index.php file with the above code.
Array
(
[id] => 33
[first_name] => removed to not show name
[last_name] => removed to not show name
[email] => test@test.com
[timestamp] => 1437486426
)
In my footer.php file I have some jquery running a timed function every 5 seconds calling the timeout.php file.
(function poll() {
setTimeout(function() {
$.ajax({ url: "timeout.php", success: function(data) {
console.log(data);
}, dataType: "json", complete: poll });
}, 5000);
})();
The timeout php file only has this code in it:
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'));
}
For some reason I am getting the session does not exist. If I remove that part of the if statement and just test the timeout all the json array variables that call $_SESSION return null. I have no idea why this is. I appreciate your help.
In response to this being a duplicate. The original thought was that session_start() wasn't called. I had mentioned it was called in the first paragraph and it comes before all other php code. I have also confirmed that I can call the $_SESSION variable within the index page just fine. I am only getting an issue when trying to read it through my ajax function which is being called from my footer.php.