dev1234
dev1234

Reputation: 5716

PHP multiple sessions

Why am I getting only the last session's output when printing ? I need to save a session for each user id and send a password reset email. when user clicks the link and change the password I need to clear the session from server.

This is how I am doing it with PHP.

$res = array();
$uniqueId = uniqid();
echo $uniqueId . "<br>";

session_id($uniqueId);
session_start();
echo session_id() . "<br>";

$_SESSION['session_id'] = session_id();
$_SESSION['event_id'] = 'event1';
$_SESSION['user_id'] = 'user1';
$res[] = json_encode($_SESSION);

$uniqueId2 = uniqid();
echo $uniqueId2 . "<br>";
session_destroy();
session_id($uniqueId2);
session_start();
echo session_id() . "<br>";

$_SESSION['session_id'] = session_id();
$_SESSION['event_id'] = 'event2';
$_SESSION['user_id'] = 'user2';
$res[] = json_encode($_SESSION);

echo "<br>";
print_r($res);

output of the print_r:

Array ( 
    [0] => {"session_id":"5609187f586da","event_id":"event1","user_id":"user1"} 
    [1] => {"session_id":"5609187f588e1","event_id":"event2","user_id":"user2"} 
)

Now in a new page when I am trying to each the event id of both sessions like this, I only get the last session's event_id but not the both. for the first it says

Notice: Undefined index: event_id in C:\xampp\htdocs\test\test.php on line 12

This is what i am doing in new page.

$id1 = '560915a8c0875';
$id2 = '560915a8c0d51';
session_id($id1);
session_start();
echo $_SESSION['event_id'];

echo "<br>";

session_id($id2);
echo $_SESSION['event_id'];

Is this not possible with PHP or what?

Upvotes: 0

Views: 1416

Answers (1)

user2762134
user2762134

Reputation:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called. http://php.net/manual/en/function.session-destroy.php

When calling session_destroy on $id1 the data will also be cleared from the server meaning when you define the session id to $id1 it will return an empty session.

Upvotes: 1

Related Questions