-1

This is simple php code with sessions:

<?php

session_start();

function testSession() {
    //global $_SESSION;
    var_dump($_SESSION['test']);
}

if (!isset($_SESSION['test'])) {
    echo  " Nope";
    $_SESSION['test'] = " Yeap";
} else {
    testSession();
}
?>

The problem is that "$_SESSION" is not a superglobal. "$_SESSION" is undefined in testSession function scope, it is visible only in the main scope. If I uncomment "global $_SESSION" than all will work.

upd: The error is "Undefined variable: _SESSION" at line var_dump($_SESSION['test']);

upd: if you write this code:

<?php

session_start();

if (!isset($_SESSION['test'])) {
    echo  " Nope";
    $_SESSION['test'] = " Yeap";
} else {
    var_dump($_SESSION['test']);
}
?>

all will work correctly.

1 Answers1

0

Always put your session_start(); at the start of the page.

Try using:

<?php
session_start();
echo "Session test ";



function testSession() {
    //global $_SESSION;
    var_dump($_SESSION['test']);
}

if (!isset($_SESSION['test'])) {
    echo  " Nope";
    $_SESSION['test'] = " Yeap";
} else {
    testSession();
}

?>
  1. Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
  2. After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
  3. Make sure cookies are enabled in the browser you are using to test it on.
  4. Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
  5. Make sure you didn't delete or empty the session.
  6. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
  7. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  8. Make sure your file extension is .php (it happens!).

Session variables not working php