Kevin
Kevin

Reputation: 23634

Mapping sessions to users

When I login a new session is generated. How can I later know for which login the session was generated?

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

Upvotes: 0

Views: 403

Answers (1)

Philippe Gerber
Philippe Gerber

Reputation: 17846

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.

Upvotes: 2

Related Questions