tags:

views:

78

answers:

1

Once i login, a new session is generated.... how can i later know for which login the session is generated.

I am getting the session value, but how to know for which user the session is all about and redirect him to that page.

+2  A: 

You do not want to create a (new) session when the user is logging in. You create/resume the session on every page.

Here some example broken down to the essentials.

login.php

<?php
session_start();
if ($_POST['user'] == 'john' && $_POST['pwd'] == 'password') {
    $_SESSION['loggedIn']  = true;
    $_SESSION['firstname'] = 'John';
}
?>

admin.php

<?php
session_start();
if (!isset($_SESSION['loggedIn']) || !$_SESSION['loggedIn']) {
    header('location: login.php');
    exit();
}

echo 'Hello ' . $_SESSION['firstname'] . '!';
?>
  • A user visits admin.php
  • session_start() creates a new session. All data ($_SESSION) is stored on the server. A new cookie with the session's id is stored client-side.
  • The user is redirected to login.php in order there is no $_SESSION['loggedIn'] key set to true
  • session_start() revives the session by the cookie sent by the browser
  • The user submits a form and authenticates. Inside the $_SESSION array we note this.
  • User goes back to admin.php and can now access the page.
Philippe Gerber