I understand that PHP stores a user’s session id in a cookie called “PHPSESSID” which is stored in the client’s browser and is matched against the session on the server to be able to relate the 2. After closing the browser
the session info dissapears but the cookie on the client remains. Is it possible to use this cookie to restore the old session? Or does all the session data get deleted from the server the moment the client closes their browser?
I had this on my page first:
session_start();
$_SESSION['message'] = 'Hello';
echo $_SESSION['message']; // outputs hello
then I changed the page to:
$old_session = session_id();
session_id($old_session);
session_start();
echo $_SESSION['message'];
Then I closed the browser and reopened it to this page and got these errors:
Warning: session_start() [function.session-start]: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in C:\xampp\htdocs\localhost\test.php on line 5
Notice: Undefined index: message in C:\xampp\htdocs\localhost\test.php on line 7
How exactly does one retrieve old session info after closing the browser, is it even possible?
A session does exactly what it says on the tin – exists for the duration of the client’s session. A browsing session by definition (such as there is one) ends when you close the browser.
Cookie-based sessions work by setting a cookie that has a lifetime defined in PHP as
0– this means that the browser should destroy the cookie when the browser is closed. Once the cookie has been destroyed, the session ID is not sent in any subsequent server requests, so the session data will not be available in your PHP script.However, the session data is not destroyed at the server side at the moment the user closes the browser, as you suggested – this is impossible, because the client does not notify the server that it has been closed. Instead, the session data at the server side has a TTL (time-to-live) which has a default value of 15 minutes. After this has expired, the data may be deleted at any time by the session garbage collector. In theory this could be some considerable time, but in practice on a busy server the data will be deleted within a couple of minutes of the TTL expiring.
However, PHP cannot make the session data available unless it has the session ID, and it will not have the session ID if the cookie has been destroyed, which as I say, should happen when the user closes their browser.
So the short answer to the question
How can I restore a PHP session?is: You can’t