Session_start doesn't work :(

I start a new session with: session_start();

then I set some session variables like this:

$_SESSION['name']=$_POST['name'];

      

and some other variables.

At the bottom of the page, I set the title to another page:

header('location: index.php');
exit();

      

Now on a new page (index.php) I cannot access my session variables eg $_SESSION['name']

.

What happened?

Thank.

+2


source to share


2 answers


Are you calling session_start()

in your other pages where you are trying to access your written variables $_SESSION

? You will need to do this before trying to read anything, for example:



session_start();
$blah = $_SESSION['blah'];

      

+7


source


This is a known issue in PHP, HTTP or whoever you want to blame. Basically, you cannot set cookies and redirect using HTTP in the same request. When you start a session that hasn't been created yet, you send a cookie.

Two options:

  • start a session elsewhere, or
  • send either JavaScript that redirects or use a meta tag.


Example:

<?php /* set session cookies */ ?>
<script>window.location.replace("index.php");</script>

      

+4


source







All Articles