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.
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 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'];
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();