skip to Main Content

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.

2

Answers


  1. Typically session_start() is put at the very top of the code, outside of the html tags and within its own php tags. It looks like yours is within the html and that might be causing the problem.

    Login or Signup to reply.
  2. 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()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search