PHP Sessions

Sessions are a way to save visitor's informations while he is connected to your website. Session is a number of variables that contain informations about the visitor like his name, username, ID ...

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 !
This small php function tells php to start a new session with the visitor, or to load all session's variables if the session is already started.

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' ;
?>
Get Session Variables:
To get the value of a session variable:
<?php
$myvariable = $_Session['variable_name'] ;

// for example:
$myname = $_Session['name'] ;
echo $myname ;
?>
Check if a Session Variable exist:
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.

1 comments:

Anonymous said...

nice blog.. thanks for visit my blog so I have the CMS that I Made You can download or see at shofura.com

Thanks