Home Tutorial Php Examples Custom Session Handler

 
 

Custom Session Handler
Posted on: July 31, 2009 at 12:00 AM
Advertisement
In this example you will learn how to use custome session handler in PHP.

Custom Session Handlers

session_set_save_handler() function is used for creating a set of user-level storage functions that is used for implementing database storage. 

In the following program you will learn how to customize your session handler. We have used opening the session, reading it, writing it, destroying it and closing the session in the following custom session handling program. The program is divided in several chunks and each chunks perform different operations. 

In the first block, the sesssavepath will save the sessionpath, and return true. 

In the second block, session file has been saved using session id. 

In the third block, function fwrite() will write the session data, which will modify the session. 

And in the fourth block, the session will get expired. 

In the fifth block, the session is set to remain maximum life time. 

After starting the session, it will entered in each block and execute.   

<?php
function open($savepath, $sessionname){
global $sesssavepath;
$sesssavepath = $savepath;
echo "sesssavepath :". $sesssavepath."<br/>";
echo "sessionname :". $sessionname."<br/>";
return(true);
}
function close(){
echo "close<br/>";
return(true);
}
function read($id){
global $sesssavepath;
echo "sesssavepath :". $sesssavepath."<br/>";
echo "id :". $id."<br/>";
$sessfile = "$sess_save_path/sess_$id";
$ss=(string) @file_get_contents($sessfile);
echo "sessfile :".$ss."<br/>";
return $ss;
}
function write($id, $sessdata){
global $sesssavepath;
$sessfile = "$sess_save_path/sess_$id";
if ($fp = @fopen($sessfile, "w")){
$return = fwrite($fp, $sessdata);
fclose($fp);
return $return;
} else {
return(false);
}
}
function destroy($id){
global $sesssavepath;
$sessfile = "$sess_save_path/sess_$id";
return(@unlink($sessfile));
}
function gc($maxlifetime){
global $sesssavepath;
foreach (glob("$sess_save_path/sess_*") as $filename) {
if (filemtime($filename) + $maxlifetime < time()) {
@unlink($filename);
}
}
return true;
}

session_set_save_handler("open", "close", "read", "write", "destroy", "gc");

session_start();
?>

Advertisement

Related Tags for Custom Session Handler:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 31, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com