Using Advanced Functions to Maintain the State of Applications with PHP Sessions - Tweaking the PHP session storage module: using the “session_set_save_handler ()” function (
Page 2 of 4 )
As you learned before, the PHP built-in session management mechanism uses as default the “/tmp” directory, in order to store session data, which is first serialized and then saved in the dynamically-generated session file (remember that session IDs also are saved in cookies in the client).
However, due to the versatility of the session module, it’s possible to modify this behavior and change the location –- and eventually the way –- in which session data is stored. Regarding this useful feature, PHP provides developers with the ability to define six callback functions, which can be used in conjunction with the “session_set_save_handler()” function, in order to construct a user-defined session storage module.
In this case, a custom callback function must be defined for each of the corresponding operations performed to manage a particular session, that is when reading, writing and destroying session data, and when the PHP built-in garbage collection mechanism is triggered. This process can be translated into the definition of six generic functions, which are listed below:
function open(){
// called when a session is opened
}
function close(){
// called when a session is closed
}
function read(){
// called when session is read
}
function write(){
// called when session is written
}
function destroy(){
// called when session is destroyed
}
function gc(){
// called when the garbage collection mechanism is triggered
}
As you can see, each of the above defined functions can be used in conjunction with the “session_set_save_handler()” function. This is handy for constructing a custom session mechanism, which eventually can be more efficient and secure that the one provided as the default by PHP.
In order to illustrate this useful concept, first I’ll show you a basic and admittedly inefficient implementation, which utilizes user-defined callback functions to store session data on a different directory. Here’s the corresponding code example:
// define new file path for storing session data
define("SESSION_PATH","c:session_path"); // double
backslashes is used on Windows systems
// not required to implement 'open()' method
function open(){
return true;
}
// not required to implement 'close()' method
function close(){
return true;
}
// define 'read()' method
function read($id){
$sessionFile=SESSION_PATH.'sess_'.$id;
if(!file_exists($sessionFile)||!
$sessionData=@file_get_contents($sessionFile)){
return "";
}
return $sessionData;
}
// define 'write()' method
function write($id,$sessionData){
if(!$fp=fopen(SESSION_PATH.'sess_'.$id,'w')){
return "";
}
return fwrite($fp,$sessionData);
}
// define 'destroy()' method
function destroy($id){
// delete session file
return unlink(SESSION_PATH.'sess_'.$id);
}
function gc($maxlifetime){
$sessionFile=SESSION_PATH.'sess_'.$id;
if(filemtime($sessionFile)>(time()-$maxlifetime)){
unlink($sessionFile);
}
return true;
}
// define custom session handling functions
session_set_save_handler
('open','close','read','write','destroy','gc');
// use sessions as one would expect
session_start();
// register some session variables
$_SESSION['firstname']='Alejandro';
$_SESSION['lastname']='Gervasio';
In short, what I’ve done with the above example is define the corresponding six callback functions that will be called up during the regular occurrence of a session. Notice that the first two functions, “open()” and close(),” don’t need to be concretely defined, thus they’re simply specified as empty.
The remaining functions take care of reading, writing and eventually deleting session data, by using the value of the constant “SESSION_PATH,” which I defined right at the beginning of the script. Of course, as I said before, this isn’t the best way of building a user-defined session storage module, but my intention is that you learn how these callback functions are used as parameters by the “session_set_save_handler()” function.
Once the “session_set_save_handler()” function is invoked with the proper callback functions, all the session data will be stored and read from the “C:session_path” directory (you can change this, in case you're using a UNIX-based operating system), which means that all the session files will be created within the mentioned directory. In case you want to see how this session mechanism works, first run the above script and use the $_SESSION superglobal array to store some session data. Then open the custom directory, and you should see that PHP has created the corresponding session files on that directory.
Nevertheless, I said the previous example was pretty useless. Why? Well, in fact there’s no need to reinvent the wheel if you just want to change the physical directory where session data is saved. Fortunately, PHP offers the “session_save_path()” function, which takes as an argument the new path where you want session data to be stored. Being aware of the existence of this function, the entire prior example might be rewritten as follows:
// use 'session_save_path()' function
session_save_path("c:session_path");// double backslashes is
used on Windows systems
session_start();
// register some session variables
$_SESSION['firstname']='Alejandro';
$_SESSION['lastname']='Gervasio';
Definitely, you’ll agree with me that the above script is much simpler to code and read. And the best thing is that you’ll get the same result, just using the “session_save_path()” function. However, the example that you learned before for using callback functions is quite good for introducing the “session_set_save_handler()” function, and serves as a nice preface for showing a more useful example of how to use this function. To see the development of a more complex example, please go ahead and keep on reading.
| | Discuss Using Advanced Functions to Maintain the State of Applications with PHP Sessions | | | | | | | In this part of the series, you'll learn how to tweak the PHP session storage... | | | | | | Hi Alejandro, I greatly appreciate your efforts in bringing us these useful... | | | | | | Hi Rafael,
Thank you for commenting on my PHP article. Regarding your question,... | | | | | | Hi Alejandro, thank you so much for the example, it worked to perfection. I'm so... | | | | | | Hi Rafael,
Thank you for the kind word on my PHP articles, and certainly I feel... | | | | | | Hello again Alejandro, I run into a bug as I got my application onto the production... | | | | | | Hi Rafael,
Thank you for posting your comments. Concerning your particular... | | | | | | Hi Alejandro, a million thanks for your help. I stayed awake for a long time last... | | | | | | Hi Rafael. I'm glad to know you fixed up the problem regarding the use of mysqli and... | | | | | | Hi alejandro
Its me again, ive been making your tutorial as my book, im working... | | | | | | Hi Alejandro,
thanks for this wonderful tutorial.
When i tried to use your... | | | | | | Hi Roy,
Thanks for posting your comments, and I’m glad to know you’re learning... | | | | | | Thansk again for the comments. In fact, $id isn't necessary when coding this... | | | | | | Hello Alejandro,
Thanks for the prompt reply. Im still confused, on your reply you... | | | | | | Hello Alejandro,
I temporarily placed this code inside the writeSession()... | | | | | | Hi Roy,
with your last example, I see the possible reason of your problem.... | | | | | | Hello alehandro...
i set up my expiry as a timestamp, and that the expiry colum... | | | | | | Hello Roy,
Thanks for the comments. Using "time()" to insert your timestamps is a... | | | | | | >>> Post your comment now! | | | | | |
|
 |