How to add session to mysql database, and add session to mysql database

Source: Internet
Author: User

How to add session to mysql database, and add session to mysql database

We know that session is a session technology used to share data across scripts or to detect and track user statuses.

How the session works

(1) When a session is enabled for the first time, a unique identifier is stored in a local cookie.

(2) first use the session_start () function. PHP loads the stored session variables from the session repository.

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

(4) When PHP script execution ends, session variables that have not been destroyed will be automatically stored in the session library under a certain local path. session in the INI file. save_path is specified. It can be loaded and used when you browse the Web page next time.

Sessions are stored in files on the server. Therefore, due to the large number of files in the session, it may cause pressure to query and read session files. Generally, we have three solutions.

1. Use File layering (Disadvantage: I/O operation is a bottleneck of the system, and this problem cannot be avoided even if it is layered)

2. Put the session into the database

3. Put the session in the memory (non-Relational Database) (Disadvantage: high requirements for server memory)

As the number of sessions increases, management is no longer convenient.

Therefore, we chose a compromise method to store the session into the mysql database, which is the focus of our discussion.

Create a table management session.

 

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

For this storage mechanism, you only need to add the session_set_save_handler () function to the file.

<? Php ini_set ("session. save_handler "," user "); // session. gc_probability = 1 molecule 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 period session_set_save_handler ("open", "close", "read", "write", "destroy", "gc "); // connect to the database function open () {@ $ link = mysql_connect ('2017. 0.0.1 ', 'root', 'root'); mysql_query ('set names Utf8'); mysql_query ('use wangbin'); // <span> the open callback function is similar to a class constructor and is called when a session is opened. This is the first called callback function to automatically start a session or call session_start () to manually start a session. If the callback function is successful, TRUE is returned. Otherwise, FALSE is returned. </Span >}function close () {mysql_close (); // <span> the close callback function is similar to the class destructor. It is called after the write callback function is called. After the session_write_close () function is called, the close callback function is also called. If the callback function is successful, TRUE is returned. Otherwise, FALSE is returned. </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 the session contains data, the read callback function must return the string after the session data encoding (serialization. </Span> </li> <li class = "alt"> <span> if no data exists in the session, the read callback function returns an empty string. </Span> </li> <li class = "alt"> <span> after the session is automatically started or the session starts manually by calling the session_start () function, </span> </li> <li class = "alt"> <span> PHP calls the read callback function internally to obtain session data. Before calling read, PHP calls the open callback function. </Span> </li> <li class = "alt"> <span> the serialized string format returned by the read callback must be exactly the same as that when the write callback function saves data. </Span> </li> <li class = "alt"> <span> PHP automatically deserializes the returned string and fills in the $ _ SESSION super global variable. </Span> </li> <li class = "alt"> <span> although the data looks similar to the serialize () function, you must note that, they are different. </Span> </li> <li class = "alt"> <span> see session. serialize_handler. </Span> </li> </ol>} function write ($ sess_id, $ sess_data) {$ SQL = "insert into 'session '(session_id, session_data, session_time) values ('$ sess_id', '$ sess_data', now () on duplicate key update session_data = '$ sess_data', session_time = now ()"; // This is for gc () return mysql_query ($ SQL);/* <span> the write callback function is called when the session saves data. This callback function receives the current session id and the serialized string in $ _ SESSION as the parameter. The process of serializing session data is completed by PHP according to the value set by session. serialize_handler. </Span> <span> serialized data is stored together with session IDs. When the read callback function is called to obtain data, the returned data must be exactly the same as the data passed into the write callback function. </Span> <span> PHP calls this callback function after the script is executed or the session_write_close () function is called. Note: after calling this callback function, PHP calls the close callback function internally. </Span> Note: <span> PHP calls the write callback function after the output stream is written and closed. Therefore, the debugging information in the write callback function is not output to the browser. If you need to use the debug output in the write callback function, we recommend that you write the debug output to the file. </Span> */} function destroy ($ sess_id) {echo _ FUNCTION __; $ SQL = "delete from 'session 'where session_id =' $ sess_id '"; return mysql_query ($ SQL);/* <span> This callback function is called when the session_destroy () function is called or the session_regenerate_id () function is called and the destroy parameter is set to TRUE. If the callback function is successful, TRUE is returned. Otherwise, FALSE is returned. </Span> */} function gc ($ sess_id) {$ maxlifetime = ini_set ("session. gc_maxlifetime "); echo _ FUNCTION __; $ SQL =" delete from 'session 'where now ()-session_time>' $ maxlifetime' "; return mysql_query ($ SQL ); /* <span> to clear the old data in the session, PHP calls the garbage collection callback function from time to time. 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. If the callback function is successful, TRUE is returned. Otherwise, FALSE is returned. </Span> */} header ("content-type: text/html; charset = utf8"); session_start (); $ _ SESSION ['name'] = 'aa'; // echo session_id (); echo $ _ SESSION ['name'];

Summary:

1. When the session is opened, the session_start () function is executed in syntax. The session mechanism of php reads the cookie on the browser, which is expressed as $ _ cookie ['phpsessid '] in syntax.

2. Find the session data stored on the server based on the cookie.

3. deserialize session data and assign the value to the variable $ _ SESSION.

4. Subsequent operations on the variable $ _ SESSION are performed on the variable and the session file is not updated.

5. Whether the session_destroy () function is executed. If yes, delete the session file on the server.

6. When the script ends, determine whether the sessin file exists or whether the session_destroy () method has been executed. If not, write the data in the $ _ SESSION variable to the session file. If it has been executed, nothing will be done.

The above is to sort out the information for adding sessions to the mysql database. For more information, see.

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.