Home > Article > Backend Development > PHP uses the session_set_save_handler() function to save the session to the MySQL database_PHP tutorial
PHP saves the session in the form of a file by default, which only consumes the space of the file It can be used on very small windows, but if we use the file system on uinx or liux, the file space overhead of such a file system is very large. However, the session must be used all the time, and a lot of Users have to create a lot of session files, which brings performance problems to the entire server.
On the other hand, if the server adopts a cluster method, the consistency of the session cannot be maintained, so we are ready to use a database to save the session. In this way, no matter how many servers are used at the same time, just save their sessions Saving it on a database server can ensure the integrity of the session. Please read on for details on how to implement it.
By default, PHP saves sessions in file format. We can see this line in the PHP configuration file PHP.ini:
session.save_handler="files"
This means that the session is saved in a file. If we want to save it in a database, we need to change it to user mode and change it to
session.save_handler="use"
That’s it, but this only means that we do not use files to store sessions. We also need to select a database and create a database table.
To establish the database and the table structure of the database, we can use any database that PHP can use. Because the combination of PHP and mysql is the best, I will use mysql as an example. Of course, you can change the name to another database according to your needs.
Create database
create database 'session';
Create table structure
create table 'session'( id char(32) not null , 'user 'char(30), data char(3000) ,primary key ('id') );
PHP save session and write PHP file
<?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 id='$id'")) { 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 id='$id'")) { return true; } else { return false; } } function destroy($id) { if ($result = mysql_query("delete * from session where id='$id'")) { 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 it as session_user_start.php.
Now our PHP session saving work has been completed. As long as you include session_user_start.php when you need to use the session. Note, This file must include , and then use it in the same way as using the file session.
SessionMysql.class.php
<?php /** * SessionMysql 数据库存储类 */ defined('IN_QIAN') or exit('Access Denied'); class SessionMysql { public $lifetime = 1800; // 有效期,单位:秒(s),默认30分钟 public $db; public $table; /** * 构造函数 */ public function __construct() { $this->db = Base::loadModel('SessionModel'); $this->lifetime = Base::loadConfig('system', 'session_lifetime'); session_set_save_handler( array(&$this, 'open'), // 在运行session_start()时执行 array(&$this, 'close'), // 在脚本执行完成 或 调用session_write_close() 或 session_destroy()时被执行,即在所有session操作完后被执行 array(&$this, 'read'), // 在运行session_start()时执行,因为在session_start时,会去read当前session数据 array(&$this, 'write'), // 此方法在脚本结束和使用session_write_close()强制提交SESSION数据时执行 array(&$this, 'destroy'), // 在运行session_destroy()时执行 array(&$this, 'gc') // 执行概率由session.gc_probability 和 session.gc_divisor的值决定,时机是在open,read之后,session_start会相继执行open,read和gc ); session_start(); // 这也是必须的,打开session,必须在session_set_save_handler后面执行 } /** * session_set_save_handler open方法 * * @param $savePath * @param $sessionName * @return true */ public function open($savePath, $sessionName) { return true; } /** * session_set_save_handler close方法 * * @return bool */ public function close() { return $this->gc($this->lifetime); } /** * 读取session_id * * session_set_save_handler read方法 * @return string 读取session_id */ public function read($sessionId) { $condition = array( 'where' => array( 'session_id' => $sessionId ), 'fields' => 'data' ); $row = $this->db->fetchFirst($condition); return $row ? $row['data'] : ''; } /** * 写入session_id 的值 * * @param $sessionId 会话ID * @param $data 值 * @return mixed query 执行结果 */ public function write($sessionId, $data) { $userId = isset($_SESSION['userId']) ? $_SESSION['userId'] : 0; $roleId = isset($_SESSION['roleId']) ? $_SESSION['roleId'] : 0; $grouId = isset($_SESSION['grouId']) ? $_SESSION['grouId'] : 0; $m = defined('ROUTE_M') ? ROUTE_M : ''; $c = defined('ROUTE_C') ? ROUTE_C : ''; $a = defined('ROUTE_A') ? ROUTE_A : ''; if (strlen($data) > 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' => $a, 'data' => $data, ); return $this->db->insert($sessionData, 1, 1); } /** * 删除指定的session_id * * @param string $sessionId 会话ID * @return bool */ public function destroy($sessionId) { return $this->db->delete(array('session_id' => $sessionId)); } /** * 删除过期的 session * * @param $lifetime session有效期(单位:秒) * @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!
new SessionMysql();Articles you may be interested in