Parsing php session_set_save_handler function of mysql

  • 2020-06-23 00:03:51
  • OfStack


<?php 
/*============================ Document describing ======================================== 
@filename:     session.class.php 
@description:   The database holds online users session , to achieve the online user function!  
@notice:       session Expiration time 1 Hours as our site is used cookie (Effective time is 1 Hours) login.                  
         So we only record the login time of the user, not the refresh 1 Time to update 1 time                  
         Delete from the database session The recorded action occurs after the user has timed out to execute the file or to exit normally ( session_destory )   
@database:     database:sessions  field:sessionid(char32),uid(int10),last_visit(int10) 
=============================================================================
*/
 class session { 
     private $db; 
     private $lasttime=3600;// Time out: 1 hours 
      function session(&$db) { 
         $this->db = &$db;
         session_module_name('user'); //session File saving mode, this is a must! Unless the Php.ini It's set in the file 
         session_set_save_handler( 
             array(&$this, 'open'), // In the run session_start() When performing 
              array(&$this, 'close'), // When the script execution is complete or invoked session_write_close()  or  session_destroy() When implemented , In all session The operation is performed after completion  
             array(&$this, 'read'), // In the run session_start() When performing , Because in the session_start when , Will go to read The current session data 
             array(&$this, 'write'), // This method is used at the end of the script session_write_close() Forced to submit SESSION Data time execution 
              array(&$this, 'destroy'), // In the run session_destroy() When performing 
              array(&$this, 'gc') // Execution probability is determined by session.gc_probability  and  session.gc_divisor The value of the decision , Timing is in open,read after ,session_start Will be executed sequentially open,read and gc
         ); 
         session_start(); // It's also necessary. Open it session Must be in session_set_save_handler Behind the execution 
     } 
        function unserializes($data_value) { 
         $vars = preg_split( 
             '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/', 
             $data_value, -1, PREG_SPLIT_NO_EMPTY | 
             PREG_SPLIT_DELIM_CAPTURE 
         ); 
         for ($i = 0; isset($vars[$i]); $i++) { 
             $result[$vars[$i++]] = unserialize($vars[$i]); 
         } 
         return $result; 
     }  
     function open($path, $name) { 
         return true; 
     } 
     function close() { 
         $this->gc($this->lasttime);
         return true; 
     } 
    function read($SessionKey){
         $sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1"; 
         $query =$this->db->query($sql);
         if($row=$this->db->fetch_array($query)){
           return $row['uid'];
         }else{
             return ""; 
         }
              } 
     function write($SessionKey,$VArray) { 
         require_once(MRoot.DIR_WS_CLASSES .'db_mysql_class.php');
        $db1=new DbCom();
       // make a connection to the database... now
        $db1->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
        $db1->query("set names utf8");
        $this->db=$db1;
        $SessionArray = addslashes($VArray);
         $data=$this->unserializes($VArray);   
                          $sql0 = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1"; 
         $query0 =$this->db->query($sql0);
         if($this->db->num_rows($query0)<=0){
             if (isset($data['webid']) && !empty($data['webid'])) { 
                $this->db->query("insert into `sessions` set `session_id` = '$SessionKey',uid='".$data['webid']."',last_visit='".time()."'");
             }    
                    return true;
         }else{
             /*$sql = "update `sessions` set "; 
             if(isset($data['webid'])){
             $sql .= "uid = '".$data['webid']."', " ;
             }
             $sql.="`last_visit` = null " 
                   . "where `session_id` = '$SessionKey'"; 
                               $this->db->query($sql); */
             return true; 
         }    
     } 
   function destroy($SessionKey) { 
      $this->db->query("delete from `sessions` where `session_id` = '$SessionKey'"); 
      return true; 
    } 
    function gc($lifetime) {
        $this->db->query("delete from `sessions` where unix_timestamp(now()) -`last_visit` > '".$this->lasttime."'");
        return true;
    } 
     } 
 ?>

Here are the configuration instructions for session in ES2en.ini:
session.save_handler = "files"
The name of the processor that stores and retrieves the data associated with the session. The default is a file ("files").
If you want to use a custom processor, such as a database-based one, you can use "user".
One use PostgreSQL processor: http: / / sourceforge net/projects/phpform ext /

session.save_path = "/tmp"
Parameters passed to the storage processor. For the files processor, this value is the path to create the session data file.
Windows defaults to the temporary folder path.
You can define the path using the pattern "N[MODE]/path" (N is 1 integer).
N represents a subdirectory that USES the DEPTH of the N layer rather than storing all data files in one directory.
[MODE] optional, must use base 8, default 600(=384), represents the maximum number of session files saved per directory.
This is a great idea to improve a lot of session performance.
Note 0: The double quotation marks around "N[MODE]/path" cannot be omitted.
Note 1: [MODE] does not overwrite the process's umask.
Note 2: php does not automatically create these folder structures. Create using the ES48en_files.sh script in the ext/session directory.
Note 3: If the folder can be accessed by insecure users (such as the default "/tmp"), security holes will be created.
Note 4: When N > Automatic garbage collection will fail at 0. See the section on garbage collection below.

session.name = "PHPSESSID"
The session ID identifier used in cookie contains only letters and Numbers.

session.auto_start = Off
Automatically initializes the session when the customer visits any page, which is disabled by default.
Because the class definition must be loaded before the session starts, you cannot store objects in the session if this option is turned on.

session.serialize_handler = "php"
The processor used to serialize/deserialize data, php, is the standard serialization/deserialization processor.
You can also use "php_binary". When WDDX support is enabled, only "wddx" will be used.

session.gc_probability = 1
session.gc_divisor = 100
Defines the probability of starting the garbage collector at each initialization session.
The collection probability is calculated as follows: ES83en.gc_ES85en/session.gc_ES88en
The more frequently you visit the session page, the less likely it should be. The recommended value is 1/1000-5000.

session.gc_maxlifetime = 1440
After the number of seconds indicated by this parameter, the saved data is treated as' garbage 'and cleaned up by the garbage collector.
The criterion is the last time the data was accessed (in the case of FAT file system, the last time the data was refreshed).
If multiple scripts share the same session. save_path directory but session. gc_maxlifetime directory,
The minimum value of all ES104en.gc_ES106en directives will prevail.
If you use multilevel subdirectories to store data files, the garbage collector does not start automatically.
You must use one of your own shell scripts, cron items, or other methods to perform garbage collection.
For example, the following script is equivalent to setting "session.gc_ES114en =1440" (24 minutes) :
cd /path/to/sessions find -cmin +24 | xargs rm

session.referer_check =
Session ID is considered invalid if the "Referer" field in the request header does not contain the string specified here.
Note: Session ID will still be considered valid if the "Referer" field does not exist in the request header at all.
The default is null, meaning no checks are made (all are considered valid).

session.entropy_file = "/dev/urandom"
Additional external high-entropy resources (files) for creating session ID,
For example, "/dev/random" or "/dev/urandom" on UNIX systems

session.entropy_length = 0
The number of bytes read from a high-entropy resource (suggested value: 16).

session.use_cookies = On
Whether to use cookie to save the session ID on the client side

session.use_only_cookies = Off
Whether to save the session ID on the client side using cookie only
Turning this option on avoids the security issues associated with passing sessions using URL.
But disabling the Cookie client will make the session not work.

session.cookie_lifetime = 0
Pass the Cookie period of validity (seconds) for session ID, with 0 being valid only for the duration of browser opening.

session.cookie_path = "/"
Pass the Cookie action path for session ID.

session.cookie_domain =
Pass the Cookie scope of session ID.
The default null represents the host name generated according to the cookie specification.

session.cookie_secure = Off
Whether to send cookie only over a secure connection (https).

session.cookie_httponly = Off
Whether to add the httpOnly flag to cookie (HTTP protocol access only),
This results in the client script (JavaScript, etc.) not being able to access the cookie.
Turning this command on effectively prevents session hijacking via the XSS attack.

session.cache_limiter = "nocache"
Set to {nocache|private|public} to specify the cache control mode for session pages,
Or set to null to prevent caching disabled commands from being sent in the http reply header.

session.cache_expire = 180
Specify the duration of the session page in client cache (minutes)
session.cache_limiter =nocache, this setting is invalid.

session.use_trans_sid = Off
Whether to display SID(session ID) in URL using plain code.
The default is disabled because it poses a security risk to your users:
1 - the user may contain effective sid URL through email/irc/QQ/MSN... Ways to tell others.
2- URL containing valid sid may be saved on a public computer.
3- Users may save URL with fixed sid in their favorites or browsing history.
URL-based session management is always more risky than ES239en-based session management, so it should be disabled.

session.bug_compat_42 = On
session.bug_compat_warn = On
The previous version of PHP4.2 had an unindicated "BUG" :
The global session variable is allowed to be initialized even if register_globals=Off,
If you use this feature in es254EN 4.3 or later, it will display a warning.
It is recommended to close the "BUG" and display a warning.

session.hash_function = 0
A hash algorithm for generating SID. SHA-1 is more secure
0: MD5 (128 bits)
1: SHA-1 (160 bits)
SHA-1 is recommended.

session.hash_bits_per_character = 4
Specifies how much bit is saved per character in the SID string,
These 2 base Numbers are the result of the hash function.
4: 0-9, a-f
5: 0-9, a-v
6: 0-9, a-z, A-Z, "-", ","
The recommended value is 5

url_rewriter.tags = "a=href,area=href,frame=src,form=,fieldset="
This instruction belongs to the PHP core, not the Session module.
Specifies which HTML tags to override to include SID(valid only if ES293en.use_trans_ES296en =On)
form and fieldset are special:
If you include them, the URL rewrite will add 1 hidden" < input > ", which contains information that should have been added to URL.
To comply with XHTML, remove the form entry and add it before and after the form field < fieldset > The tag.
Note: All valid entries require an equal sign (even if no value follows).
The recommended value is "a=href,area=href,frame=src,input=src,form=fakeentry".


Related articles: