Peter Stuart
Peter Stuart

Reputation: 2434

PHP not starting session?

I have written a simplte PHP login script which starts a session:

//Lets start our session
//Create our session
$_SESSION['token'] = md5($user['salt'].$user['user_id'].$user['username']);
$_SESSION['id'] = $user['user_id'];
$_SESSION['username'] = $user['username'];
header('Location: index.php');
die();

And on the index file I have this code:

if(array_key_exists('id', $_SESSION) && array_key_exists('username', $_SESSION)):
    echo 'Welcome user';
else:
    include 'login.php';
endif;

Everytime the user logs in it doesn't start a session. I made sure the password and usename is on the database (using my own validation script). Can anyone see anything I am missing.

Thanks

Peter

Upvotes: 2

Views: 619

Answers (3)

Robert Van Sant
Robert Van Sant

Reputation: 1507

do you have your session_start(); somewhere? i don't see it in your code sample.

Upvotes: 1

dimme
dimme

Reputation: 4424

Add session_start(); on the top of all files where you are using sessions.

Upvotes: 5

Michael Berkowski
Michael Berkowski

Reputation: 270677

You missed the most important part of starting a session: session_start()

session_start();
$_SESSION['token'] = md5($user['salt'].$user['user_id'].$user['username']);
$_SESSION['id'] = $user['user_id'];
$_SESSION['username'] = $user['username'];
header('Location: index.php');
die();

And on the index page as well:

session_start();
if(array_key_exists('id', $_SESSION) && array_key_exists('username', $_SESSION)):
    echo 'Welcome user';
else:
    include 'login.php';
endif;

Upvotes: 7

Related Questions