PHP Sessions: Quick Reference

Published by Subhas Fagu on 26/04/09 01:08:04
Last edited on 27/04/09 21:00:33

Simply put a session is a variable that lasts through-out the period of a http session. It is similar to a cookie however once the browser is closed the variable is lost. If you would like variables that that last days and months then a cookie is what you are interested in.
This article is a quick how-to on working with PHP session variables, we will cover the basics to get you started.

Starting a PHP Session

You will first need to start the PHP session by inserting the following code.

session_start(); // start up your PHP session!

This registers the session with the web server and assigns a UID for the session. This UID will be stored against all your session variables.

Storing a Session Variable

Storing values to php session variables are no different from the conventional programming way of storing to variables. All session variables are stored to an associative array called $_SESSION. Below are several examples on storing and retrieving values.

//start php session
session_start();

// store session data
$_SESSION['testStrVar'] = 'Techlicity';
$_SESSION['testIntVar'] = 780700;

//retrieve data
echo "String Var = ". $_SESSION['testStrVar'];
echo "\nInt Var = ". $_SESSION['testIntVar'];

Cleaning and Destroying your Session

PHP Session data are automatically destroyed once the browser is closed, however you may wish to kill them during the user's visit, perhaps a log out feature. You can destroy individual variables or kill them all :p

session_start(); //start our session
if(isset($_SESSION['testStrVar']))
    unset($_SESSION['testIntVar']);

Notice we check if the variable is assigned a value first using PHP isset function, if you don't check first then you will receive PHP NOTICES in your log file or on screen depending on your php log level.

Below is how to destroy all php session variables associated with the site so far.

session_start();
session_destroy();
About the Author

Subhas Fagu is an energetic person who you will never catch doing the same thing twice…unless it’s working. He’s always engaged in new concepts, frameworks, operating systems, applications, you name it and you’ve got a conversation. Being a founder of Techlicity Ventures, he's been a key in the business and technical development of all previous and upcoming projects. Subhas contributes a wide variety of perspectives to all projects to ensure risk coverage and smooth deployment.

Bookmark and Share
Blog Widget by LinkWithin
blog comments powered by Disqus

Valid XHTML 1.0!