phpsessioncookieserror-handling

Why is my PHP session data not persisting across pages?


I am using PHP sessions to store user data. However, the session data is not persisting when I navigate to a different page.

Here is my code:

Page 1:
<?php
session_start();
$_SESSION['user'] = 'JohnDoe';
echo "Session set.";
?>
Page 2:
<?php
session_start();
echo $_SESSION['user'];
?>

I expected the session variable user to be available on both pages. However, on Page 2, it gives an error or outputs nothing. I ensured that session_start() is included but still face this issue.


Solution

  • session_start() only creates uniq id for session and array, but not saves it. At the end of your first script you need to use session_write_close().

    You should also check on browser side that headers of first script response contain PHP_SESSID cookie and it still alive when you request second page.

    The default lifetime of such cookie is only one browser session. If you are going to close browser, you need to make some settings on such session, for 24 hours it looks like this: session_set_cookie_params(86400);