Use the session_set_save_handler () function in php to save the session to the MySQL database instance.

Source: Internet
Author: User
Tags php session php and mysql
This article mainly introduces how to use the session_set_save_handler () function in php to save the session to the MySQL database instance. This article also shows how to save the Session to the Mysql database storage class.

This article mainly introduces how to use the session_set_save_handler () function in php to save the session to the MySQL database instance. This article also shows how to save the Session to the Mysql database storage class.

By default, the PHP session is saved as a file, which can be used only on windows with a low file space overhead, however, if we use a file system on the uinx or liux, the file space overhead of such a file system is very large, but the session must be used all the time, A large number of users need to create a lot of session files, which brings performance problems to the entire server.

On the other hand, if the server starts to adopt the cluster mode, the session consistency cannot be maintained. Therefore, we are ready to use the database mode to save the session. In this way, no matter how many servers are used at the same time, you only need to save their sessions on a database server to ensure the integrity of the sessions. Continue with the implementation steps.

By default, PHP saves session files. We can see this line in PHP preparation file PHP. ini:

The Code is as follows:


Session. save_handler = "files"


This means to use files to save sessions. To use a database to store sessions, we need to change it to user mode and change it

The Code is as follows:


Session. save_handler = "use"


However, this only means that we have not stored the session in the file mode. We also need to select a database and create a database table.

Create a table structure for databases and databases. We can use any database that PHP can use. Because PHP and mysql have the best combination, I will use mysql as an example, you can change the name of another database as needed.

Create a database

The Code is as follows:


Create database 'session ';


Create Table Structure

The Code is as follows:


Create table 'session '(id char (32) not null, 'user' char (30), data char (3000), primary key ('id '));


PHP saves session and writes PHP files

The Code is as follows:


<? Php
$ Con = mysql_connect ("127.0.0.1", "user", "pass ");
Mysql_select_db ("session ");
Function open ($ save_path, $ session_name ){
Return (true );
}
Function close (){
Return (true );
}
Function read ($ id ){
If ($ result = mysql_query ("select * from session where ")){
If ($ row = mysql_felth_row ($ result )){
Return $ row ["data"];
}
} Else {
Return "";
}
}
Function write ($ id, $ sess_data ){
If ($ result = mysql_query ("update session set data = '$ sess_data 'where ")){
Return true;
} Else {
Return false;
}
}
Function destroy ($ id ){
If ($ result = mysql_query ("delete * from session where ")){
Return true;
} Else {
Return false;
}
}
Function gc ($ maxlifetime ){
Return true;
}
Session_set_save_handler ("open", "close", "read", "write", "destroy", "gc ");
Session_start ();
// Proceed to use sessions normally

Save as session_user_start.php.

Now we have completed saving the session in PHP, as long as you need to include session_user_start.php when using the session. note: This file must be included in the first line of the file, and can be used in the same way as the session of the file.

The above is just a simple tutorial. in practical applications, You can encapsulate it more professionally. The reference code is as follows:

SessionMysql. class. php

The Code is as follows:


<? Php
/**
* SessionMysql database storage class
*/

Defined ('in _ QIAN ') or exit ('Access Denied ');

Class SessionMysql {

Public $ lifetime = 1800; // validity period. Unit: seconds. The default value is 30 minutes.
Public $ db;
Public $ table;

/**
* Constructor
*/
Public function _ construct (){
$ This-> db = Base: loadModel ('sessionmodel ');
$ This-> lifetime = Base: loadConfig ('system', 'session _ lifetime ');
Session_set_save_handler (
Array (& $ this, 'open'), // run
Array (& $ this, 'close'), // It is executed when the script is executed or session_write_close () or session_destroy () is called, that is, it is executed after all session operations are completed.
Array (& $ this, 'read'), // It is executed when session_start () is run, because the current session data is read during session_start.
Array (& $ this, 'write'), // this method is executed when the script ends and session_write_close () is used to force the SESSION data to be submitted.
Array (& $ this, 'deststroy'), // execute when running session_destroy ()
Array (& $ this, 'gc ') // The execution probability is determined by the session. gc_probability and session. the value of gc_pisor is determined by the time when session_start runs open, read, and gc successively after open and read.
);
Session_start (); // This is also required. To open a session, it must be executed after session_set_save_handler.
}
/**
* Session_set_save_handler open method
*
* @ Param $ savePath
* @ Param $ sessionName
* @ Return true
*/
Public function open ($ savePath, $ sessionName ){
Return true;
}
/**
* Session_set_save_handler close Method
*
* @ Return bool
*/
Public function close (){
Return $ this-> gc ($ this-> lifetime );
}
/**
* Read session_id
*
* Session_set_save_handler read Method
* @ Return string reads session_id
*/
Public function read ($ sessionId ){
$ Condition = array (
'Where' => array (
'Session _ id' => $ sessionId
),
'Fields' => 'data'
);
$ Row = $ this-> db-> fetchFirst ($ condition );
Return $ row? $ Row ['data']: '';
}
/**
* Write the session_id Value
*
* @ Param $ sessionId session ID
* @ Param $ data value
* @ Return mixed query execution result
*/
Public function write ($ sessionId, $ data ){
$ UserId = isset ($ _ SESSION ['userid'])? $ _ SESSION ['userid']: 0;
$ RoleId = isset ($ _ SESSION ['roleid'])? $ _ SESSION ['roleid']: 0;
$ GrouId = isset ($ _ SESSION ['groupid'])? $ _ SESSION ['groupid']: 0;
$ M = defined ('route _ m ')? ROUTE_M :'';
$ C = defined ('route _ C ')? ROUTE_C :'';
$ A = defined ('route _ ')? ROUTE_A :'';
If (strlen ($ data) & gt; 255 ){
$ Data = '';
}
$ Ip = get_ip ();
$ SessionData = array (
'Session _ id' => $ sessionId,
'User _ id' => $ userId,
'IP' => $ ip,
'Last _ visit' => SYS_TIME,
'Role _ id' => $ roleId,
'Group _ id' => $ grouId,
'M' => $ m,
'C' => $ c,
'A' => $,
'Data' => $ data,
);
Return $ this-> db-> insert ($ sessionData, 1, 1 );
}
/**
* Delete the specified session_id.
*
* @ Param string $ sessionId session ID
* @ Return bool
*/
Public function destroy ($ sessionId ){
Return $ this-> db-> delete (array ('session _ id' => $ sessionId ));
}
/**
* Delete expired sessions
*
* @ Param $ lifetime session validity period (unit: seconds)
* @ Return bool
*/
Public function gc ($ lifetime ){
$ ExpireTime = SYS_TIME-$ lifetime;
Return $ this-> db-> delete ("'last _ visit' <$ expireTime ");
}
}

Just instantiate this class somewhere in the system file!

The Code is as follows:


New SessionMysql ();

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.