Php uses the session_set_save_handler () function to save the session to the MySQL database. _ PHP Tutorial

Source: Internet
Author: User
Tags php session
Php uses the session_set_save_handler () function to save the session to the MySQL database. Php uses the session_set_save_handler () function to save the session to the MySQL database. by default, PHP saves the session by using the file method, this is only a small file space overhead. php uses the session_set_save_handler () function to save the session to the MySQL database.

By default, the PHP session is saved as a file, which can be used only on windows with a low File space overhead, however, if we use a file system on the uinx or liux, the file space overhead of such a file system is very large, but the session must be used all the time, A large number of users need to create a lot of session files, which brings performance problems to the entire server.

On the other hand, if the server starts to adopt the cluster mode, the session consistency cannot be maintained. Therefore, we are ready to use the database mode to save the session. in this way, no matter how many servers are used at the same time, you only need to save their sessions on a database server to ensure the integrity of the sessions. continue with the implementation steps.

By default, PHP saves session files. we can see this line in PHP preparation file PHP. ini:

Session. save_handler = "files"

This means to use files to save sessions. to use a database to store sessions, we need to change it to user mode and change it

Session. save_handler = "use"

However, this only means that we have not stored the session in the file mode. we also need to select a database and create a database table.

Create a table structure for databases and databases. we can use any database that PHP can use. because PHP and mysql have the best combination, I will use mysql as an example, you can change the name of another database as needed.

Create a database

Create database 'session ';

Create table structure

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

PHP saves session and writes PHP files

 

Save as session_user_start.php.

Now we have completed saving the session in PHP, as long as you need to include session_user_start.php when using the session. note: This file must be included in the first line of the file, and can be used in the same way as the session of the file.

The above is just a simple tutorial. in practical applications, you can encapsulate it more professionally. the reference code is as follows:

SessionMysql. class. php

  Db = Base: loadModel ('sessionmodel'); $ this-> lifetime = Base: loadConfig ('system', 'session _ lifetime '); session_set_save_handler (array (& $ this, 'open'), // execute array (& $ this, 'close') when running session_start '), // when the script execution is complete or session_write_close () or session_destroy () is called, that is, the array (& $ this, 'read') is executed after all session operations are completed '), // run session_start (). because session_start reads the current session data array (& $ this, 'write '), // This method ends with the script and uses the session _ Write_close (): execute array (& $ this, 'deststroy') when forcibly submitting SESSION data, // execute array (& $ this, 'gc ') when running session_destroy ') // The execution probability is set by session. gc_probability and session. the value of gc_pisor is determined by the timing. after open and read, session_start will successively execute open, read, and gc); session_start (); // This is also required to open the session, must be executed after session_set_save_handler}/*** session_set_save_handler open method ** @ param $ savePath * @ param $ sessionName * @ return true */public function open ($ savePath, $ SessionName) {return true;}/*** session_set_save_handler close method ** @ 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 session_id value ** @ 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 ['giuid'])? $ _ SESSION ['groupid']: 0; $ m = defined ('Route _ m ')? ROUTE_M: ''; $ c = defined ('Route _ c ')? ROUTE_C: ''; $ a = defined ('Route _ ')? 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 sessions ** @ 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!

New SessionMysql ();

Articles you may be interested in
  • Php obtains all the files in the directory and saves the results to the array program.
  • Php uses array_flip to implement array key-value exchange to remove array duplicate values
  • Php uses the filter function to verify the mailbox, url, and IP address
  • Steps for synchronizing and backing up mysql databases in windows
  • Php uses the ZipArchive function to compress and decompress files.
  • Functions and usage of the php get_headers function
  • PHP uses Curl Functions to Capture webpages and download files with multiple threads
  • Use the PHP function memory_get_usage to obtain the current PHP memory consumption for program performance optimization.

The merge () function saves the session to the MySQL database. by default, PHP saves the session by using the file method, which only consumes a small amount of space in the file...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.