Home Backend Development PHP Tutorial PHP implements multiple web servers to share SESSION data-session data is written to mysql database_PHP tutorial

PHP implements multiple web servers to share SESSION data-session data is written to mysql database_PHP tutorial

Jul 13, 2016 pm 05:39 PM
mysql php session web shared write accomplish data database server

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

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

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.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 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.

See all articles