Table of Contents
Use the session_set_save_handler() function in php to save the session to the MySQL database instance, sessionhandler
How to use database to implement PHP to save SESSION details??
Session saving problem in PHP
Home Backend Development PHP Tutorial Use the session_set_save_handler() function in PHP to save the session to a MySQL database instance, sessionhandler_PHP tutorial

Use the session_set_save_handler() function in PHP to save the session to a MySQL database instance, sessionhandler_PHP tutorial

Jul 13, 2016 am 10:14 AM
handler mysql php save session set database

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

PHP saves sessions by default in the form of files. This can only be used on Windows where the file space overhead is very small, but if we use the file system on uinx or liux, The file space overhead of such a file system is very large. However, sessions must be used all the time. A large number of users will create a lot of session files, which will bring 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:

Copy code The code is as follows:

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
Copy code The code is as follows:

session.save_handler="use"

That's fine, but this just means that we don't 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

Copy code The code is as follows:

create database 'session';

Create table structure
Copy code The code is as follows:

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

PHP save session and write PHP file
Copy code The code is as follows:

$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 that this file must be included in the first line of the file, and then like Just use the same method as the file session.

The above is just a simple tutorial. In actual applications, it can be packaged more professionally. The reference code is as follows:

SessionMysql.class.php

Copy code The code is as follows:

/**
* SessionMysql database storage class
​*/

defined('IN_QIAN') or exit('Access Denied');

class SessionMysql {

public $lifetime = 1800; // Validity period, unit: seconds (s), default 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'), // Executed when running session_start()
array(&$this, 'close'), // Executed when the script execution is completed or session_write_close() or session_destroy() is called, that is, it will be executed after all session operations are completed
Array(&$this, 'read'), // Executed when running session_start(), because when session_start, the current session data will be read
Array(&$this, 'write'), // This method is executed when the script ends and session_write_close() is used to force the submission of SESSION data
array(&$this, 'destroy'), // Executed when running session_destroy()
Array(&$this, 'gc') // The execution probability is determined by the values ​​of session.gc_probability and session.gc_divisor. The timing is after open and read. Session_start will execute open, read and gc in succession
);
Session_start(); // This is also necessary. To open the session, it must be executed after 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);
}
/**
* Read session_id
*
* session_set_save_handler read method
* @return string read 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 value of session_id
*
* @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['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);
}
/**
* 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 session
*
* @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!

Copy code The code is as follows:

new SessionMysql();

How to use database to implement PHP to save SESSION details??

I hope you can fully master this knowledge through the relevant methods and techniques introduced in this article. PHP $con =mysql_connection("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 ?

Session saving problem in PHP

PHP saves sessions by default in the form of files. This can only be used on Windows where the file space overhead is very small, but if we use the file system on uinx or liux, The file space overhead of such a file system is very large. However, sessions must be used all the time. A large number of users will create a lot of session files, which will bring performance problems to the entire server. On the other hand, if If the server adopts the cluster method, the consistency of the session cannot be maintained, so we are ready to use the database method to save the session. In this way, no matter how many servers are used at the same time, they only need to save their sessions on one database server. The integrity of the session can be saved. Please continue reading for details on how to implement it.
By default, PHP sessions are saved in the file format. We can see a line like this in the PHP configuration file php.ini, session.save_handler="files", which means using files. To save the session, if we want to use the database to save it, we need to change it to user mode and rename it session.save_handler="use". However, this only means that we do not use files to store sessions. We also need to Select the database and the tables to create the database.
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 for the example. Of course, you can change the name to another database according to your needs. At the same time, because MySQL does not have transaction functions, it is faster than other databases. However, saving the session does not require transaction processing, so I think it is better here.
Create database, CREATE DATABASE 'session'; Create table structure CREATE TABLE 'session'( id CHAR(30) NOT NULL , 'user 'CHAR(30), data CHAR(3000) ,PARMIRY BY ('id') );
Write php file
$con =mysql_connection("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...The rest of the text>>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907278.htmlTechArticleThe session_set_save_handler() function is used in php to save the session to the MySQL database instance. The sessionhandler PHP saves the session by default. Saved as a file, this is only in the file...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

How to analyze the execution plan of MySQL query How to analyze the execution plan of MySQL query Apr 29, 2025 pm 04:12 PM

Use the EXPLAIN command to analyze the execution plan of MySQL queries. 1. The EXPLAIN command displays the execution plan of the query to help find performance bottlenecks. 2. The execution plan includes fields such as id, select_type, table, type, possible_keys, key, key_len, ref, rows and Extra. 3. According to the execution plan, you can optimize queries by adding indexes, avoiding full table scans, optimizing JOIN operations, and using overlay indexes.

What are the advantages of using MySQL over other relational databases? What are the advantages of using MySQL over other relational databases? May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

See all articles