0

I'm creating a PHP session, username and all, but when I redirect with header(foo.php), the $_SESSION variable appears empty, even though before redirecting it appears properly filled when checking with var_dump.

First I create the session:

   $_SESSION['loggedin'] = true;
   $_SESSION['username'] = $username;
   $_SESSION['start'] = time();
    $_SESSION['expire'] = $_SESSION['start'] + (5 * 60);
   echo "Bienvenido! " . $_SESSION['username'];

   header('location:login-success.php');
   exit();

On the next page I start session on top of the page, no HTML above, no nothing:

<?php
    session_start();
    if(!isset($_SESSION['username'])){
        echo "nope";
    }
?>

The output is always "nope". I've tried on my localhost and on a remote host, several browsers, cookies are enabled. $_SESSION appears empty when checking with var_dump now.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
sergiotbh
  • 188
  • 1
  • 5
  • 13
  • 1
    Upon creating the session, have you started it? Are you sure you're not accidentally destroying it? – Janno May 25 '17 at 08:29
  • 1
    Did you do a `session_start()` in the script that is loading the data into the session – RiggsFolly May 25 '17 at 08:30
  • `session_start();` needed on each page on top where you are going to deal with `SESSION` in any way.So add it in your first page – Alive to die - Anant May 25 '17 at 08:33
  • 1
    @AlivetoDie that is exactly what I was missing. I feel so dumb because it took me hours and I couldn't figure out on my own. Thank you. – sergiotbh May 25 '17 at 08:38

1 Answers1

3

session_start(); needed on each page on top where you are going to deal with SESSION in any way (create,update,delete).

So add it in your first page like below:-

<?php
  session_start();
  $_SESSION['loggedin'] = true;
  $_SESSION['username'] = $username;
  $_SESSION['start'] = time();
  $_SESSION['expire'] = $_SESSION['start'] + (5 * 60);
  echo "Bienvenido! " . $_SESSION['username'];

  header('location:login-success.php');
  exit();
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98