How to join Mysql Library in session _mysql

Source: Internet
Author: User
Tags garbage collection session id php session php script sessions string format server memory

We know that session is a conversation technique that enables you to share data across scripts or to detect the state of a tracked user.

The working principle of Session

(1) When a session is first enabled, a unique identity is stored in a local cookie.

(2) First using the Session_Start () function, PHP loads the session variables that have been stored from the session warehouse.

(3) When executing a PHP script, register the session variable by using the Session_register () function.

(4) When the PHP script executes, the unsaved session variable is automatically saved in the session library under a local path, which can be specified by the Session.save_path in the php.ini file and can be loaded the next time the page is browsed.

The session is stored in the server-side file, so it is possible that sessions may have a lot of file size, which can create pressure when querying the file and reading. In general, we have three different solutions

1. Using file layering (disadvantage: I/O operations are a bottleneck in the system, even if tiering does not avoid this problem)

2. Put the session into the database

3. Place session in memory (non-relational database) (disadvantage: High server memory requirements)

As the session increases, management is already inconvenient.

So we choose a compromise approach, the session will be stored in the MySQL database, which is the focus we want to talk about.

Set up a table to manage sessions.

Change the session's storage mechanism so that the session no longer exists in the file but is stored.

More of the storage mechanism, you just need to add the function Session_set_save_handler () to the file.

<?php ini_set ("Session.save_handler", "user");  
Session.gc_probability = 1 Molecular ini_set ("session.gc_probability", 1);  
Session.gc_divisor = 1000 Denominator ini_set ("Session.gc_divisor", 2); Session.gc_maxlifetime = 1440 garbage collection time, session validity Session_set_save_handler ("open", "close", "read", "write", "destroy" 
, "GC");  
 Connection database function open () {@ $link = mysql_connect (' 127.0.0.1 ', ' root ', ' root ');  
 mysql_query (' Set names UTF8 '); 
 mysql_query (' use Wangbin '); 
 The <span>open callback function is similar to the constructor of a class and is invoked when the session is opened. This is the first callback function invoked after the session is started automatically or by calling Session_Start () manually. This callback function operation successfully returns TRUE, otherwise returns false. 
 </span>} function Close () {mysql_close (); The <span>close callback function is similar to a class destructor. 
 Called after the write callback function call. When the Session_write_close () function is called, the close callback function is also called. This callback function operation successfully returns TRUE, otherwise returns false.   
 </span>} function read ($sess _id) {$sql = "Select Session_data from ' session ' where session_id = ' $sess _id '";  
 $result = mysql_query ($sql); if ($rows = Mysql_fetch_assoc ($result)) {return $rows [' Session_data ']; 
 } else{return '; <ol class= "Dp-py" start= "1" ><li class= "alt" ><span> if there is data in the session, the read callback function must return the string after encoding (serializing) the session data. </span></li><li class= "alt" ><span> if there is no data in the session, the read callback function returns an empty string. </span></li><li class= "alt" ><span> after starting the session automatically or by calling the Session_Start () function,</span> </li><li class= "alt" ><span>php internally calls the read callback function to get session data. 
PHP calls the open callback function before calling read. </span></li><li class= "alt" ><span>read the serialized string format returned by the callback must be in exactly the same format as the write callback function when the data was saved. 
</span></li><li class= "alt" ><span>php automatically deserializes the returned string and fills the $_session super global variable. 
</span></li><li class= "alt" ><span> although the data looks similar to the serialize () function, it should be recalled that they are different. </span></li><li class= "alt" ><span> please refer to: Session.serialize_handler. </span></li></ol>} function Write ($sess _id, $sess _data) {$sql = INSERT INTO ' Session ' (Session_i D,session_data,sessioN_time values (' $sess _id ', ' $sess _data ', Now ()) on the duplicate key update session_data = ' $sess _data ', session_time = Now () " ; 
 This is for GC () return mysql_query ($sql); /* <span> calls the write callback function when the session holds data. 
 This callback function receives the current session ID and the string after the data serialization in $_session as a parameter. The process of serializing session data is done by PHP based on the Session.serialize_handler set value. The </span> <span> serialized data is associated with the session ID to save. When the read callback function is invoked to fetch data, the returned data must be fully consistent with the data passed in the write callback function. 
 </span><span> PHP calls this callback function after the script finishes executing or when the Session_write_close () function is called. Note that after this callback function is called, the close callback function is called inside of PHP. 
 </span> Note: <span>php will call the write callback function after the output stream has been written and closed, so debug information in the write callback function is not exported to the browser. If you need to use debug output in the write callback function, it is recommended that you write the debug output to a file.  
 </span>/} function Destroy ($sess _id) {echo __function__;  
 $sql = "Delete from ' session ' where session_id = ' $sess _id '"; 
 return mysql_query ($sql); /* <span> calls this callback function when the Session_destroy () function is invoked, or when the session_regenerate_id () function is invoked and the destroy parameter is set to TRUE. This callback function operation successfully returns TRUE, otherwise returns FALSE. </span> * 
  
The function gc ($sess _id) {$maxlifetime = Ini_set ("Session.gc_maxlifetime");  
 Echo __function__;  
 $sql = "Delete from ' Sessions ' where Now ()-session_time > ' $maxlifetime '"; 
 return mysql_query ($sql); 
 /* <span> in order to clean up the old data in the session, PHP calls the garbage collection callback function at regular intervals. 
 The call cycle is controlled by the session.gc_probability and Session.gc_divisor parameters. 
 The lifetime parameter passed into this callback function is set by Session.gc_maxlifetime. This callback function operation successfully returns TRUE, otherwise returns FALSE.  
</span>/} header ("Content-type:text/html;charset=utf8");  
Session_Start ();  
$_session[' name ']= ' AA ';  
Echo session_id ();  echo $_session[' name '];

Summary session operation Mechanism:

1. When the session is opened, the syntax executes the function session_start (), and the PHP session mechanism reads the cookie from the browser side, which is syntactically expressed as $_cookie[' Phpsessid '.

2. Locate the session data stored on the server side according to the cookie.

3. Deserialize the session data and assign the value to the variable $_session.

4. After the operation of the variable $_session is the operation of the variable, will not update the session file.

5. Whether the Session_destroy () function is executed, and if so, delete the server-side session file.

6. At the end of the script, determine if there is a Sessin file, or whether the Session_destroy () method has been executed. If it is not executed, the data in the $_session variable is written to the session file. If you do, then do nothing.

The above is the session to join the MySQL library data collation, the need for friends can refer to.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.