Using Sessions in PHP
Session variables hold information about one single user, and are available
to all pages in one application.
over internet to maintain state of the user we will use sessions, sessions are
temporary, by a unique id web server will keep the user data in the web server
with which user state can be maintained across the pages in the website.
before we start using the session variables we have to start the
session with
session_start()
note:we have to start the session before the beginning of static HTML
Once we start the session then playing with session is easy
Creating Session Variable
To create Session variable
1
2
3
| $_SESSION[variablename]=value of the session variable
//$_SESSION['username']="supreme"; |
Retrieving Session Variable
To retrieve Session variable
targetvariable=$_SESSION[variable];
ex: user=$_SESSION["username"];
A sime Program usingSession (Refresh.php)
1
2
3
4
5
6
7
| <?php
session_start();
if (isset($_SESSION["refresh"]))
$_SESSION["refresh"]=date("Y-m-d H:i:s A",time());
echo "You Came to this Page at : ".$_SESSION["refresh"]."<br>Now, Current Time is ".date("Y-m-d H:i:s A",time());
?> |
paste this code as refresh.php and refresh the page and you will come to
know the difference
Its always better to check and use the session variable like with
isset function we can know weather the session variable is available or
not.If session variable exists we can start using it otherwise assaign it and
then go for it.
ex: the same way in the above refresh.php page
Clearing the Session variables
we can clear either single session variable or we can destroy the total
session
unlike cookies, we have unset function to clear the session variables
1
| unset($_SESSION["session_variable_name"]) |
this will be used when you want to clear one particular session
variable
1
| unset($_SESSION["refresh"]); |
to destroy current session totally
1
2
3
4
| session_destroy();
//ex: session_destroy(); |