PHP Tutorials

XMLStyleSoldierFlowerMonkey

Sessions

This tutorial will teach an alternative and effective solution to cookies in PHP which might actually be better for your website and security.

Spreadshirt
A session is defined in PHP and throughout the Internet as a unique visit to a particular website and it's subsidaries. How can sessions in PHP help you out? Well, let's say you have a dynamic website where you want to have a person sign in with a username and password. Once he's in, you want him to be able to access all parts of your website using that name and password.

There are several ways to "remember" his username and password while he's at your site. One way is to use cookies. The advantage of using cookies is that once he logs in, the cookie stores the visitors information on that computer for as long as the duration of the cookie, even if the session is over. For example, if he logs in and browses around your site and then closes IE, and comes back tomorrow to your page, it'll still remember his name and password. The obvious disadvantage of cookies is that it's a security hazard. Also, some people have cookies disabled so it may not be a viable solution. PHP Sessions are a safer, always working method of storing variables in PHP throughout the duration of the visitors stay.

Alright, let's get started. The first thing you have to place is:
<?
session_start();  
header("Cache-control: private"); 
?>
The session_start() and the header has to be placed on the TOP (before any output) of every page you want these variables to follow along with the user. Once you have started the session, to add variables to the session, all you have to do is use the _Session varible. For example, if you want to have a username variable with a value of "Bobert", you write:
<?
$_SESSION["username"] = "Bobert"; 
?>
Now, just think of $_SESSION["username"] as any other variable like $username. You can do anything you want with it, and it'll follow around your website from one page to another. A session is ended whenever the visitor leaves your site, if you ever want to destroy/kill a variable inside the session, just use this command:
<?
unset($_SESSION["variable"]); 
?>
and replace variable, with the name of the variable you want to delete. If you want to end the session all together while still keeping the visitor on your site, use:
<?
session_destroy(); 
?>
That logs off the user. I hope this tutorial helped you in realizing an alternative, safer way PHP has come up to deal with site global variables than cookies.

Discuss this tutorial »
Written by: Akash Goel
Back to PHP TutorialsTop


Copyright © 2000-2008 Spoono, LLC. All rights reserved.
Network: Reseller Web Hosting by Spoono Host | Spoonloads | Absolute Cross
Terms of Service | Privacy Policy.

kdfj