PHP using the Session_set_save_handler () function to save the session to the MySQL database instance _php instance

Source: Internet
Author: User
Tags session id php and mysql sessions create database

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

On the other hand, if the server does not maintain session consistency when it is clustered, so we are ready to use the database to save sessions so that no matter how many servers are used at the same time, As long as their session saved on a database server can guarantee the integrity of sessions, how to achieve the implementation please continue to see.

PHP Save session By default is the file way to save, we in the PHP configuration file php.ini can see such a line:

Copy Code code as follows:

session.save_handler= "Files"

This means that the use of documents to save the session, to use the database to save, we need to modify into user mode, change to
Copy Code code as follows:

Session.save_handler= "Use"

On it, however, this is only to show that we do not use the file to store the session, we also have to select the database and build the database table.

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

Creating a Database

Copy Code code as follows:

Create database ' session ';

Create a table structure
Copy Code code as follows:

CREATE TABLE ' session ' (ID char (m) not null, ' user ' char (), Data char (3000), primary key (' ID '));

PHP Save session write PHP file
Copy Code code as follows:

<?php
$con = mysql_connect ("127.0.0.1", "User", "pass");
mysql_select_db ("session");
function open ($save _path, $session _name) {
return (true);
}
function Close () {
return (true);
}
function Read ($id) {
if ($result = mysql_query ("SELECT * from session where id= ' $id")) {
if ($row = Mysql_felth_row ($result)) {
return $row ["Data"];
}
} else {
Return "";
}
}
function Write ($id, $sess _data) {
if ($result = mysql_query ("Update session set Data= ' $sess _data ' where id= ' $id '))" {
return true;
} else {
return false;
}
}
function Destroy ($id) {
if ($result = mysql_query ("Delete * from session where id= ' $id")) {
return true;
} else {
return false;
}
}
Function GC ($maxlifetime) {
return true;
}
Session_set_save_handler ("Open", "close", "read", "write", "Destroy", "GC");
Session_Start ();
Proceed to use sessions normally

Save to become session_user_start.php.

Now our PHP save session work is done, as long as you need to use the session, the Session_user_ Start.php included. Note that this file must be included in the first line of the file, and then used as a method of using the session of the file.

The above is just a simple tutorial, in the actual application, you can encapsulate it more professional, the reference code is as follows:

SessionMysql.class.php

Copy Code code as follows:

<?php
/**
* Sessionmysql Database Storage class
*/

Defined (' In_qian ') or exit (' Access Denied ');

Class Sessionmysql {

Public $lifetime = 1800; Validity period, unit: seconds (s), default 30 minutes
Public $db;
Public $table;

/**
* Constructor
*/
Public Function __construct () {
$this->db = Base::loadmodel (' Sessionmodel ');
$this->lifetime = base::loadconfig (' System ', ' session_lifetime ');
Session_set_save_handler (
Array (& $this, ' Open '),//When running Session_Start ()
Array (& $this, ' close '),//executed when the script executes or invokes Session_write_close () or Session_destroy (), which is executed after all session operations have been done
Array (& $this, ' read '),//executed when running Session_Start (), because when Session_Start, read the current session data
Array (& $this, ' write '),//This method executes when the script ends and the session data is forced to be submitted using Session_write_close ()
Array (& $this, ' Destroy '),//When running Session_destroy ()
Array (& $this, ' GC ')//execution probability is determined by the value of session.gc_probability and Session.gc_divisor, the timing is Open,read, session_ The start will execute Open,read and GC successively
);
Session_Start (); It is also necessary to open the session, which must be performed after the 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 value of session_id
*
* @param $sessionId Session ID
* @param $data value
* @return Mixed Query execution results
*/
Public function Write ($sessionId, $data) {
$userId = isset ($_session[' userId '))? $_session[' userId ': 0;
$roleId = isset ($_session[' Roleid '))? $_session[' 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 ' => $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 session
*
* @param $lifetime Session duration (in seconds)
* @return BOOL
*/
Public Function GC ($LIFETIME) {
$expireTime = sys_time-$lifetime;
return $this->db->delete ("' Last_visit ' < $expireTime");
}
}

At some point in the system file, instantiate the Class!

Copy Code code as follows:

New Sessionmysql ();

Related Article

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.