The example in this article describes how to implement a custom session processor in PHP. Share it with everyone for your reference. The specific analysis is as follows:
Session custom session processor, that is to say, all various operations on the session can be decided by customizing the session. What does it mean? Let’s first look at the session.save_handler configuration in php.ini.
By default, session.save_handler = files, which means that the system-defined processor is called (the so-called processor is actually a lot of functions/methods). You can set session.save_handler to user or memcache, or even network file system (cloud computing).
session.save_handler = user: Indicates calling a custom session handler; session.save_handler = memcache: Indicates... slightly.... (roughly saved in memory, more efficient).
When setting session.save_handler = files, regarding the operation of the session, six callback functions of session.set_save_handler (see the PHP manual for details) are actually called (the so-called callback functions are called by the system and do not need to be specified). . See the code below for the six callback functions, which are also available in the PHP manual:
function open($save_path, $session_name)
{
global $sess_save_path;
$sess_save_path = $save_path;
return(true);
}
function close()
{
return(true);
}
function read($id)
{
global $sess_save_path;
$sess_file = "$sess_save_path/sess_$id";
return (string) @file_get_contents($sess_file);
}
function write($id, $sess_data)
{
global $sess_save_path;
$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "w")) {
$return = fwrite($fp, $sess_data);
fclose($fp);
Return $return;
} else {
Return(false);
}
}
function destroy($id)
{
global $sess_save_path;
$sess_file = "$sess_save_path/sess_$id";
return(@unlink($sess_file));
}
function gc($maxlifetime)
{
global $sess_save_path;
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();
// proceed to use sessions normally
?>
Of course, you can also modify the way the session is saved. The default is to save it in a file. You can save it in the database (of course it is not recommended that you do this, the database reading speed is slower), or you can set it to be saved in the memory. (The fastest speed, explained in detail in memcache related content).
I hope this article will be helpful to everyone’s PHP programming design.