Monday, September 04, 2006

Sessions


So, we've been looking a bit at session variables. The scenario:

we're displaying a screenful of data to our web site visitors (like a list of authors), and we want to give authorised users the option to edit, delete and add new records - but we want to hide these pages from the average viewer. First, we need a login screen.

A simple form asking for a user's email and password should do. When the form's submitted, these fields would be checked against a database of users. Then the magic occurs...

If the user's email and password match, we'll be setting a session variable, that will let us know that they're authorised to see the administrative pages and links.

Sessions are like server-side files that store variables that can be read from, or written to, by PHP scripts. Each session file is unique to the user that created it and can only be accessed by subsequent requests from the same user.

For our login, we'll be setting a session variable called loggedin. The first piece of code on the page, and all other pages that need to access the variables, will be:

<?php session_start(); ?>

This piece of code does one of two things. If the user does not already have a session, it creates a new session - or - if the user does already have a session it connects to the existing session file. When a new session is created, PHP session management generates a session identifier.

After calling the session_start function, we're ready to do the email/password comparison with the user details in the database (you can do that), if they match we'd set the session variable:

$_SESSION['loggedin'] = 'true';

Subsequenly we can check for this value on any page. To selectively display bits of html (links to edit and delete functions, for example) we might add:

<?php
session_start();
if ($_SESSION['loggedin'] == 'true') {
echo 'Edit>';
}
?>

If we were restricting access to a whole page (say the add, edit or delete pages), we might add some code like this:

<?php
session_start();
if ($_SESSION['loggedin'] != 'true') {
header("location:login.php");
}
?>

This code checks to see if the session variable loggedin is set to true. If not, it redirects the user to the login page.



Thanks to iconjon for the pic

No comments: