PHP uses the Session_set_save_handler () function to save the session to the MySQL database _php tutorial

Source: Internet
Author: User
Tags php and mysql

PHP uses the Session_set_save_handler () function to save the session to the MySQL database


PHP saves the session by default is the way to save the file, which is only available on Windows with a small amount of space on the file, but if we adopt Uinx or Liux file system, the file space overhead of such file system is very large, However, the session is to be used all the times, a large number of users will create a lot of session files, so that the entire server brings performance problems.

On the other hand, if the server is clustered, it cannot maintain session consistency, so we are ready to use the database to save the session, so that no matter how many servers are used at the same time, Just keep their session on a database server to ensure that the session is complete, how to implement please continue to see.

PHP Save session By default is the use of the file method to save, we can see in the PHP configuration file php.ini this line:

session.save_handler= "Files"

This means that the use of files to save the session, to use the database to save, we need to modify the user mode, change to

Session.save_handler= "Use"

Yes, but it just means that we don't store the session in a file, we also choose the database and the tables that build the database.

To build the database and database table structure, we can use any PHP can be used by the database, because the combination of PHP and MySQL is best, I use MySQL to do the example, of course, according to your needs can be renamed to another database.

Create a database

Create database ' session ';

CREATE TABLE structure

CREATE TABLE ' session ' (ID char (+) NOT NULL, ' user ' char (+), data char (+), primary key (' ID '));

PHP Save session Write PHP file

 

Save As session_user_start.php.

Now the work of our PHP save session has been completed, as long as you need to use the session, the session_user_start.php included in. Note that this file must be included in the first line of the file , And then it's just like using a file's session as a way to use it.

The above is just a simple tutorial, in the actual application, you can package it more professional, 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 (),//During script execution completion or call session _write_close () or Session_destroy () is executed, that is, after all sessions are executed, the array (& $this, ' read '),//is executed when running Session_Start (), Because in Session_Start, will go to read the current session data array (& $this, ' write '),//This method at the end of the script and use Session_write_close () Enforce Array (& $this, ' destroy ') when submitting session data,//execute Array (& $this, ' GC ') when running Session_destroy ()//execution probability by session.gc_ The value of probability and session.gc_divisor is determined, the timing is after Open,read, Session_Start will be executed successively Open,read and GC); Session_Start (); This is also necessary, open session, must be executed behind 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-&GT;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 ($sess Ionid, $data) {$userId = Isset ($_session[' userid '])? $_session[' userid ']: 0; $roleId = isset ($_session[' Roleid '))? $_ses sion[' 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 ' and $roleId, ' group_id ' and $grouId, ' m ' + $m, ' C ' + $c, ' a ' and ' = ' $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 expiration (in seconds) * @return Bool*/public function gc ($lifetime) {$expireTime = SYS _time-$lifetime; return $this->db->delete ("' Last_visit ' < $expireTime");}}

Instantiate this class somewhere in the system file!

New Sessionmysql ();

Articles you may be interested in

    • PHP gets all the files in the directory and saves the results to an array of programs
    • PHP uses Array_flip to implement array key-value Exchange to remove array duplicate values
    • Php method for verifying mailboxes, URLs, and IP addresses using the filter function
    • Master-Slave synchronous backup steps for MySQL database in Windows environment
    • PHP using ziparchive function to realize the compression and decompression of files
    • function and usage of PHP get_headers functions
    • PHP uses Curl Functions to crawl Web pages and download files in multiple threads
    • Use PHP function memory_get_usage to get the current PHP memory consumption to achieve program performance optimization

http://www.bkjia.com/PHPjc/905118.html www.bkjia.com true http://www.bkjia.com/PHPjc/905118.html techarticle PHP uses the Session_set_save_handler () function to save the session to the MySQL database, PHP save the session by default is the way to save the file, which is only 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.