Table of Contents
Foreword:
1. Create a session table
2、定义会话函数:
3、使用新会话处理程序
4、测试使用
Home Backend Development PHP Tutorial PHP database save session session

PHP database save session session

Apr 03, 2018 am 11:10 AM
php session database

This article introduces about saving sessions in PHP database. Now I share it with everyone. It can also be a reference for friends in need. Let’s take a look together


Foreword:


By default, PHP will save all session data in text files on the server. These files are usually saved on the server. Inside the temporary directory on.

Then why do we need to save the session in the database?

  1. The main reason: to improve the security of the system. On a shared server, without special settings, all websites will use the same temporary directory, which means that dozens of programs are reading and writing files in the same location. Not only was the speed slowed down, but it was also possible for someone else to steal my site's user data.

  2. Saving session data to the database can also make it easier to search for more information about web site sessions. We can query the number of active sessions (the number of users online at the same time), and we can also query Session data is backed up.

  3. If my site runs on multiple servers at the same time, then a user may send multiple requests to different servers during a session, but if the session data is saved in On a certain server, other servers cannot use these session data. If one of my servers only plays the role of a database, wouldn't it be very convenient for you to save all session data in the database?

For more understanding of PHP session, please refer to this blog. Thoroughly understand PHP’s SESSION mechanism

1. Create a session table

Since the session data is stored on the server, and an index (sessionID) is stored on the client, this index corresponds to a certain piece of session data on the server. Therefore, the two fields that the table must contain are id and data, and the session will have expiration time, so there is another field here which is last_accessed. Here I build the table under the test database:

CREATE TABLE sessions(
    id CHAR(32) NOT NULL,
    data TEXT,
    last_accessed TIMESTAMP NOT NULL,    PRIMARY KEY(id)
);
Copy after login

PHP database save session session

PS: If the program needs to save a large amount of data in the session, the data field may need to be defined as MEDIUMTEXT or LONGTEXT type.

2、定义会话函数:

这里我们主要有两个步骤:

  1. 定义与数据库交互的函数

  2. 使PHP能使用这些自定义函数

在第二步中,是通过调用函数 session_set_save_handler()来完成的,调用它需要6个参数,分别是 open(启动会话)、close(关闭会话)、read(读取会话)、write(写入会话)、destroy(销毁会话)、clean(垃圾回收)。

我们新建php文件 sessions.inc.php ,代码如下:

<?php$sdbc = null;  //数据库连接句柄,在后面的函数里面让它成为全局变量//启动会话function open_session(){
    global $sdbc;      //使用全局的$sdbc
    $sdbc = mysqli_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;lsgogroup&#39;, &#39;test&#39;);     //数据库 test
    if (!$sdbc) {        return false;
    }    return true;
}//关闭会话function close_session(){
    global $sdbc;    return mysqli_close($sdbc);
}//读取会话数据function read_session($sid){
    global $sdbc;    $sql = sprintf("SELECT data FROM sessions WHERE id=&#39;%s&#39;", mysqli_real_escape_string($sdbc, $sid));    $res = mysqli_query($sdbc, $sql);    if (mysqli_num_rows($res) == 1) {        list($data) = mysqli_fetch_array($res, MYSQLI_NUM);        return $data;
    } else {        return &#39;&#39;;
    }
}//写入会话数据function write_session($sid, $data){
    global $sdbc;    $sql = sprintf("INSERT INTO sessions(id,data,last_accessed) VALUES(&#39;%s&#39;,&#39;%s&#39;,&#39;%s&#39;)", mysqli_real_escape_string($sdbc, $sid), mysqli_real_escape_string($sdbc, $data), date("Y-m-d H:i:s", time()));    $res = mysqli_query($sdbc, $sql);    if (!$res) {        return false;
    }    return true;
}//销毁会话数据function destroy_session($sid){
    global $sdbc;    $sql = sprintf("DELETE FROM sessions WHERE id=&#39;%s&#39;", mysqli_real_escape_string($sdbc, $sid));    $res = mysqli_query($sdbc, $sql);    $_SESSION = array();    if (!mysqli_affected_rows($sdbc) == 0) {        return false;
    }    return true;
}//执行垃圾回收(删除旧的会话数据)function clean_session($expire){
    global $sdbc;    $sql = sprintf("DELETE FROM sessions WHERE DATE_ADD(last_accessed,INTERVAL %d SECOND)<NOW()", (int)$expire);    $res = mysqli_query($sdbc, $sql);    if (!$res) {        return false;
    }    return true;
}//告诉PHP使用会话处理函数session_set_save_handler(&#39;open_session&#39;, &#39;close_session&#39;, &#39;read_session&#39;, &#39;write_session&#39;, &#39;destroy_session&#39;, &#39;clean_session&#39;);//启动会话,该函数必须在session_set_save_handler()函数后调用,不然我们所定义的函数就没法起作用了。session_start();//由于该文件被包含在需要使用会话的php文件里面,因此不会为其添加PHP结束标签
Copy after login

PS:

  1. 处理“读取”函数外,其他函数必须返回一个布尔值,“读取”函数必须返回一个字符串。

  2. .每次会话启动时,“打开”和“读取”函数将会立即被调用。当“读取”函数被调用的时候,可能会发生垃圾回收过程。

  3. 当脚本结束时,“写入”函数就会被调用,然后就是“关闭”函数,除非会话被销毁了,而这种情况下,“写入”函数不会被调用。但是,在“关闭”函数之后,“销毁”函数将会被调用。

  4. .session_set_save_handler()函数参数顺序不能更改,因为它们一一对应 open 、close、read、、、、

  5. 会话数据最后将会以数据序列化的方式保存在数据库中。

3、使用新会话处理程序

使用新会话处理程序只是调用session_set_save_handler()函数,使我们的自定义函数能够被自动调用而已。其他关于会话的操作都没有发生变化(以前怎么用现在怎么用,我们的函数会在后台自动被调用),包括在会话中存储数据,访问保存的会话数据以及销毁数据。

在这里,我们新建 sessions.php 文件,该脚本将在没有会话信息时创建一些会话数据,并显示所有的会话数据,在用户点击 ‘log out’(注销)时销毁会话数据。

代码:

<?php//引入sessions.inc.php文件,即上面的代码require(&#39;sessions.inc.php&#39;);?><!doctype html><html lang=&#39;en&#39;><head>
    <meta charset="utf-8">
    <title>DB session test</title></head><body><?php//创建会话数据if(empty($_SESSION)){    $_SESSION[&#39;blah&#39;] = "umlaut";    $_SESSION[&#39;this&#39;] = 12345;    $_SESSION[&#39;that&#39;] = &#39;blue&#39;;    echo "<p>Session data stored</p>";
}else{    echo "<p>Session data exists:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">".print_r($_SESSION,1)."
Copy after login
Copy after login

"; }if(isset($_GET['logout'])){ //销毁会话数据 session_destroy(); echo "

session destroyed

"; }else{ echo "log out"; }echo "

session data :

".print_r($_SESSION,1)."
Copy after login

";echo ''; session_write_close(); //下面重点解析?>

解析 session_write_close():

顾名思义,该函数就是先写入会话数据,然后关闭session会话,按道理这两步在脚本执行完后会自动执行,为什么我们还要显式调用它呢?因为这里涉及到了数据库的连接!

由于我们知道,PHP会在脚本执行完后自动关闭数据库的所有连接,而同时会话函数会尝试向数据库写入数据并关闭连接。这样一来就会导致会话数据没法写入数据库,并且出现一大堆错误,例如write_session()、close_session()函数中都有用到数据库的连接。

为了避免以上说的问题,我们在脚本执行完之前调用 session_write_close()函数,他就会调用“写入”函数和“关闭”函数,而此时数据库连接还是存在的!

PS:在使用header()函数重定向浏览器之前也应该调用session_write_close()函数,假如有数据库的操作时!

4、测试使用

在浏览器中打开 sessions.php,刷新页面,然后再看看数据库有没有添加数据。在另一个浏览器打开 sessions.php ,看看数据库中有没有添加另一条数据。。。。。

本博客主要是参考自《深入理解PHP高级技巧、面向对象与核心技术》,希望能帮到大家。

相关推荐:

PHP开发Session原理以及使用详解



The above is the detailed content of PHP database save session session. For more information, please follow other related articles on the PHP Chinese website!

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 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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

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

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles