I have been having problems with php session variables, so I brought it down to this simple code:
session_start();
echo "I was: " . $_SESSION['myvar'] . "<br>";
$_SESSION['myvar'] = intval($_GET['pos']);
echo "I am: " . $_SESSION['myvar'] . "<br>";
I passed in the query string random values. I expected the "I was" statement to print the old value, then a new one is assigned (from the query string), and the new one is echoed. However, Here was my output for these two subsequent queries: $_GET['pos'] = 1 and $_GET['pos'] = 2.
#Expected output
I was
I am 1
I was 1
I am 2
#Actual output
I was 1
I am 1
I was 2
I am 2
Any ideas of why this is happening?
EDIT: From the comments, I can see that I haven't made clear how I use my original script.
1- I want to remember from what page the user is currently on. When the user requests a new page (AJAX call), the request goes through my script, I update the session variable holding the user's current page, and I echo a json_encode string, from which my javascript updates the user's page.
2- What I simulated here was:
First request: The user is not on any page, and requests page 1.
Second request: The user is on page 1 (that my script remembers with the session variable simulated here with $_SESSION['myvar']), and requests page 2. Thus, for next request, my script will know that the user is on page 2, and on and on and on.
3- What I am getting here: The user is on no page, requests page 1... But my script (for some unknown reason) thinks he is already on page 1. Same idea for page 2.
I assumed using session variables was the way to go. Was I wrong?
Thank you for your help.
EDIT(2): I tried this again the next day, but this time the script worked as I expected... Not sure what happened though.
Try to use that code to destroy session
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_unset(); session_destroy(); session_write_close(); setcookie(session_name(), '', 0, '/'); session_regenerate_id(true);
header('Location:index.php');
exit();
The value of SESSION['myvar'] isset for the life of your session .ie browser is open. That maybe the reason why you re getting such weird results.