You may see the how sessions work when you login is some websites, and they show up your name in all pages.
Start a session:
Every time you want to use sessions, the first thing you should remember is to add this script before any other one:
<?php session_start(); ?> // this must be in the first line !
Add variables and values to session:
To add a new variable or write to a session variable, use this:
<?php
$_Session['variable_name'] = 'value' ;
// for example:
$_Session['name'] = 'yourname' ;
?>
$_Session['variable_name'] = 'value' ;
// for example:
$_Session['name'] = 'yourname' ;
?>
To get the value of a session variable:
<?php
$myvariable = $_Session['variable_name'] ;
// for example:
$myname = $_Session['name'] ;
echo $myname ;
?>
$myvariable = $_Session['variable_name'] ;
// for example:
$myname = $_Session['name'] ;
echo $myname ;
?>
Its sometimes usefull to check if a session variable exist:
if(isset($_SESSION['variable_name']))
echo 'Variable "variable" exist and it's value: ' . $_SESSION['variable_name'];
?>
We will see in the nex post how to delete a session variable or a total session.