ohhreeohh
ohhreeohh

Reputation: 45

Session does not save values between pages

I'm encountering a strange error that has been on and off throughout my entire coding process.

On every page, i require_once at the top of the page an authentication.php.

In there would be this:

if(!isset($_SESSION)) session_start();
if(!isset($_SESSION['test'])) 
{ 
    $_SESSION['auth'] = randString(); //this is my own method creating a random auth id
    $_SESSION['test'] = "Session is set and remembered.";   
}

However, my auth continues to generate a random id every refresh.

Around this point i discovered that my session stores a "PHPSESSID" in cookie form, and changed it to

if(!isset($_SESSION['auth'])) 
{ 
    $_SESSION['auth'] = $_COOKIE['PHPSESSID'];
}
else
{
    echo "hi";  
}

Though this changed my session id from changing every refresh, it never does echo 'hi', which comes to the conclusion that the session values aren't being stored.

Does anyone know what I'm doing wrong?

Upvotes: 0

Views: 253

Answers (2)

cream
cream

Reputation: 1129

if you don't call session_start() at the beginning of each page it will not store the session variable. If you're including this code in many pages, it should be safe to just call it again. I've never experienced any problems doing this. Just nix the first line and add session_start()

Sessions

Upvotes: 0

Matt Cain
Matt Cain

Reputation: 5768

session_start() needs to be called at the top of the page, even after the session has started.

Remove the if at the beginning: if(!isset($_SESSION))

Upvotes: 1

Related Questions