Monday, October 16, 2006

Using sessions in PHP

Building web applications with membership management is one of the most frequent tasks that every programmer does. Managing membership data, such as username, password and the member's profile with sessions in PHP is the easiest and simplest solution, although it is not the only one.

With this tutorial, I assume you are using PHP 4.1.0 or the later. The first thing that we should know to use sessions is that you have to initialize the session.

session_start();

Any script which has that line would make the script available to register a new session or read an existing session which we have defined on another page.

Enough of the blah blah stuff, shall we now go to the example stuff?

<?php// page1.phpsession_start();

$_SESSION["real_name"] = "Ashraf Gheith ";

print "<a href='page2.php'>Go to this page</a>";?>

<?php// page2.phpsession_start();print $_SESSION["real_name"];?>

The above example shows you that I create a session variable named "real_name" storing my name as the value. Then on the second page, I print out the session variable and my name will show up.

When you first access that page, it will display 1. Try to refresh the page and the number will grow.

To destroy or delete an existing session variable, you can use the unset command.

unset($_SESSION["session_name"]);

Or if you want to delete all session variables (and the session itself), you can do it by using the destroy command.

session_destroy();

The destroy command is usually used to log-off a user from the membership area. Let's make a membership area for our example.

In the first page, I stated that sessions are usually used to create a membership management. Now, I want to show you a little snippet to create a login system, which you have to complete to create your own membership management.

In the above example, we have built three pages. The first page is functions.php. In this page we build all the functions to do login checking, the login and the login detector.

The second page is login.php. We will show the login form to our user and do some processes to register sessions when they have passed the login check.

Third and the last page is the sample of how to use the system. This page is only available when user has logged in or has the session variable "member_id" with some value, not null.

Well, now it's time for blah blah stuff. I hope now you know how sessions work in PHP. Sessions are a variable which act as a global variable and can be accessed from any page you want in your domain and also can be declared or destroyed from any page.