search
HomeBackend DevelopmentPHP TutorialPHP implements multiple web servers to share SESSION data-session data is written to mysql database_PHP tutorial

PHP enables multiple web servers to share SESSION data (session data is written to the mysql database)

1. Origin of the problem

Slightly larger websites usually have several servers. Each server runs modules with different functions and uses different second-level domain names. For a comprehensive website, the user system is unified, that is, a set of The user name and password can be used to log in to all modules of the entire website. It is relatively easy for each server to share user data. You only need to put a database server on the back end, and each server can access user data through a unified interface. But there is still a problem, that is, after the user logs in to this server, when entering other modules of another server, he still needs to log in again. This is a one-time login, and all common problems are mapped to technology. In fact, it is between various servers. How to share SESSION data.

2. How PHP SESSION works

Before solving the problem, let’s first understand how PHP SESSION works. When the client (such as a browser) logs in to the website, the visited PHP page can use session_start() to open SESSION, which will generate the client's unique identification SESSION ID (this ID can be obtained/set through the function session_id()). The SESSION ID can be retained on the client in two ways, so that when requesting different pages, the PHP program can learn the client's SESSION ID; one is to automatically add the SESSION ID to the GET URL (this can only be done under Unix systems) (The Windows system cannot automatically add it to the URL), or in the POST form. By default, the variable name is PHPSESSID; the other is to save the SESSION ID in the COOKIE through COOKIE. By default, the name of this COOKIE is the PHPSESSID. Here we mainly use the COOKIE method for explanation, because it is widely used.

So where is the SESSION data stored? Of course it is on the server side, but it is not stored in memory, but in a file or database. By default, the SESSION saving method set in php.ini is

Files(session.save_handler = files), that is, saving SESSION data by reading and writing files, and the directory where SESSION files are saved is specified by session.save_path, and the file name starts with

 sess_ is the prefix, followed by SESSION ID, such as: sess_c72665af28a8b14c0fe11afe3b59b51b. The data in the file is the SESSION data after serialization. If there is a large number of visits,

may occur

There will be more SESSION files. In this case, you can set up a hierarchical directory to save SESSION files. The efficiency will be much improved. The setting method is: session.save_path="N;/save_path", N is the number of hierarchical levels

​, save_path is the starting directory. When writing SESSION data, PHP will obtain the client's SESSION_ID, and then use this SESSION ID to find

in the specified SESSION file saving directory.

The corresponding SESSION file will be created if it does not exist. Finally, the data will be serialized and written to the file. Reading SESSION data is a similar operation process. The read data needs to be deserialized to generate the corresponding

’s SESSION variable.

3. Main obstacles and solutions to multi-server sharing SESSION

By understanding the working principle of SESSION, we can find that by default, each server will generate a SESSION ID for the same client respectively. For example, for the same user browser, the SESSION ID generated by server A is 30de1e9de3192ba6ce2992d27a1b6a0a. The B server generates c72665af28a8b14c0fe11afe3b59b51b. In addition, PHP's SESSION data are stored separately in the file system of this server.

After identifying the problem, you can start to solve it. If you want to share SESSION data, you must achieve two goals:

One is that the SESSION ID generated by each server for the same client must be the same and can be passed through the same COOKIE, which means that each server must be able to read the same COOKIE named PHPSESSID;

Another is that the storage method/location of SESSION data must ensure that each server can access it. Simply put, multiple servers share the client's SESSION ID, and they must also share the server's SESSION

Data.

The realization of the first goal is actually very simple. You only need to specially set the domain of the COOKIE. By default, the domain of the COOKIE is the domain name/IP address of the current server. If the domain is different, Each

COOKIES set by two servers cannot access each other.

IV. Code implementation

First create a data table. The SQL statement of MySQL is as follows:

CREATE TABLE `sess` (

 `sesskey` varchar(32) NOT NULL default ,

 `expiry` bigint(20) NOT NULL default 0,

`data` longtext NOT NULL,

PRIMARY KEY (`sesskey`), KEY `expiry` (`expiry`)

 ) TYPE=MyISAM

 Sesskey is the SESSION ID, expiry is the SESSION expiration time, and data is used to save SESSION data.

By default, SESSION data is saved in file mode. If you want to save it in database mode, you must redefine the processing functions of each SESSION operation. PHP provides session_set_save_handle()

Function, you can use this function to customize the SESSION processing process. Of course, you must first change session.save_handler to user, which can be set in PHP: session_module_name(user);

Next, we will focus on the session_set_save_handle() function,

This function has six parameters: session_set_save_handler (string open, string close, string read, string write, string destroy, string gc) Each parameter is the function name of each operation. These operations are in order:

Open, close, read, write, destroy, garbage collection. There are detailed examples in the PHP manual,

Here we use OO to implement these operations. The detailed code is as follows:

 

define(MY_SESS_TIME,3600); //SESSION survival time

// Class definition

class My_Sess

 {

 /**

 * The database connection object is set as a static variable. Because it is not set as a static variable, the database connection object cannot be called in other methods. It is still unclear why

*

 * @var obj

*/

static public $db;

 /**

 * Constructor

*

* @param obj $dbname database connection object

*/

Function __construct($dbname){

Self::$db = $dbname;

 }

 /**

* Initialize the session, use the database mysql to store the session value, and use the session_set_save_handler method to implement

*

*/

Function init()

 {

 $domain = ;

//Do not use GET/POST variable method

ini_set(session.use_trans_sid,0);

//Set the maximum garbage collection lifetime

ini_set(session.gc_maxlifetime,MY_SESS_TIME);

//How to use COOKIE to save SESSION ID

ini_set(session.use_cookies,1);

ini_set(session.cookie_path,/);

//Multiple hosts share the COOKIE that saves the SESSION ID. Because I am testing on a local server, I set $domain=

ini_set(session.cookie_domain,$domain);

//Set session.save_handler to user instead of the default files

session_module_name(user);

//Define the method names corresponding to each operation of SESSION

session_set_save_handler(

Array(My_Sess,open),//corresponds to the open() method of class My_Sess, the same below.

array(My_Sess,close),

array(My_Sess,read),

array(My_Sess,write),

array(My_Sess,destroy),

array(My_Sess,gc)

 );

//session_start() must be located after the session_set_save_handler method

session_start();

 }

Function open($save_path, $session_name) {

//print_r($sesskey);

return true;

 } //end function

Function close(){

 if(self::$db){

Self::$db->close();

 }

return true;

 }

Function read($sesskey) {

 $sql = SELECT `data` FROM `sess` WHERE `sesskey`= . (self::$db->qstr($sesskey)) . AND `expiry`>= . time();

 $rs=self::$db->execute($sql);

 if($rs){

 if($rs->EOF){

return ;

 } else {//Read SESSION data corresponding to SESSION ID

 $v = $rs->fields[0];

 $rs->close();

return $v;

 }

 }

return ;

 }

Function write($sesskey,$data){

 $qkey = $sesskey;

$expiry = time()+MY_SESS_TIME;

 $arr = array(

 sesskey => $qkey,

expiry => $expiry,

data => $data);

Self::$db->replace(sess, $arr, sesskey, true);

return true;

 }

Function destroy($sesskey) {

 $sql = DELETE FROM `sess` WHERE `sesskey`=.self::$db->qstr($sesskey);

 $rs =self::$db->execute($sql);

return true;

 }

Function gc($maxlifetime = null) {

 $sql = DELETE FROM `sess` WHERE `expiry`<.time>

Self::$db->execute($sql);

// Due to frequent deletion operations on the sess table, fragmentation is easy to occur,

//So optimize the table during garbage collection.

 $sql = OPTIMIZE TABLE `sess`;

Self::$db->Execute($sql);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486277.htmlTechArticlePHP implements multiple web servers to share SESSION data (session data is written to the mysql database) 1. The origin of the problem is slightly larger Websites usually have several servers, each server running...
Statement
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment