Sunday, December 19, 2010

session using php - sample code

A session is similar as a variable that resides in the server. The sesion variable is a global variable that can be used in all pages in a website. We can hold the userids, user email , privilages etc in the session.

The following is a sample code for session hanling. We can use an object oriented programming to handle the session.

Step 1 :
The SessionManager class is the session handler file. It contains the functions to create session, to store content to session, view the session content, delete session etc.

<?php
class SessionManager
{
public function __construct()
{

}

public function getSession($name = 'admin')
{
return $this->hasSession() ? ($_SESSION[$name]) : null;
}

public function hasSession($name = 'admin')
{
return (isset($_SESSION[$name]));
}

public function createSession($content,$name = 'admin', $override = false)
{
if(!$this->hasSession() || ($this->hasSession() && $override) )
{
$_SESSION[$name] = $content;
session_write_close();
return true;
}
else
{
return false;
}
}

public function destroySession ($name = 'admin')
{
$_SESSION[$name] = null;
unset($_SESSION[$name]);

return true;
}
}
?>
The createSession function creates the session . If we pass the session name it will create a session with the passing name, otherwise it will create session with tha name as 'admin'.
The 'hasSession' function checks whether the session is existing or not. It will return true, if the session exists.The 'getSession' function returns the informations stored in the session.

The 'destroySession' function destroys the session details.

Step 2:
Create an object for the SessionManager. Here we are using conditions to display how these functions are working.


<?php
session_start();
include_once 'SessionManager.class.php';
$sess = new SessionManager();
extract($_GET);
if($type==1)
{
$advalue = array('adid'=>1,'adname'=>'main admin','privilage'=>'super','lastlogin'=> time());
$sess->createSession($advalue);
}
else if($type==2)
{
echo "<pre>";
print_r($sess->getSession());
echo "</pre>";
}
else if($type==3)
{
$sess->destroySession();
}
?>
<a href="?type=1"> Create Session </a> <br>
<a href="?type=2">View Session</a> <br>
<a href="?type=3"> Delete Session </a> <br>


Here we are storing an array in the session.