• PHP Video Tutorials

PHP - session_set_save_handler() Function



Definition and Usage

Sessions or session handling is a way to make the data available across various pages of a web application. The session_set_save_handler() function is used to set user-level session storage functions using which you can store and retrieve the data associated with the current session.

Syntax

session_cache_expire($sessionhandler [,$register_shutdown]);

Parameters

Sr.No Parameter & Description
1

sessionhandler (Mandatory)

This is an object of the class that implements the interfaces SessionHandlerInterface and SessionIdInterface.

2

register_shutdown (Optional)

If you pass value for this parameter, the session_write_close() will be registered as a register_shutdown_function() function.

Return Values

This function returns a boolean value which is TRUE in case of success or FALSE in case of failure.

PHP Version

This function was first introduced in PHP Version 4 and works in all the later versions.

Example 1

Following example demonstrates the usage of the session_set_save_handler() function.

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  	
         function open($save_path, $session_name){
            global $session_path;
            $session_path = $save_path;
            return(true);
         }
         function close() {
            return(true);
         }
         function read($id){
            global $session_path;  
            $sess_file = "$session_path/sess_$id";
            return (string) @file_get_contents($sess_file);
         }
         function write($id, $sess_data){
            global $session_path;
            $sess_file = "$session_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 $session_path;
            $sess_file = "$session_path/sess_$id";
            return(@unlink($sess_file));
         }
         function gc($maxlifetime){
            global $session_path;
            foreach (glob("$session_path/sess_*") as $filename) {
               if (filemtime($filename) + $maxlifetime < time()) {
                  @unlink($filename);
               }
            }
            return true;
         }
         $res = session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
         if($res){
            print("Successful");
         }else{
            print("A problem occurred");
         }
         session_start();
      ?>
   </body>   
</html> 

One executing the above html file it will display the following message.

Successful
php_function_reference.htm
Advertisements