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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

The page is blank after PHP is connected to MySQL. What is the reason for the invalid die() function? The page is blank after PHP is connected to MySQL. What is the reason for the invalid die() function? Apr 01, 2025 pm 03:03 PM

The page is blank after PHP connects to MySQL, and the reason why die() function fails. When learning the connection between PHP and MySQL database, you often encounter some confusing things...

Top 10 PHP CMS Platforms For Developers in 2024 Top 10 PHP CMS Platforms For Developers in 2024 Dec 05, 2024 am 10:29 AM

CMS stands for Content Management System. It is a software application or platform that enables users to create, manage, and modify digital content without requiring advanced technical knowledge. CMS allows users to easily create and organize content

See all articles