Home > Backend Development > PHP Tutorial > Use the session_set_save_handler() function in PHP to save the session to a MySQL database instance, sessionhandler_PHP tutorial

Use the session_set_save_handler() function in PHP to save the session to a MySQL database instance, sessionhandler_PHP tutorial

WBOY
Release: 2016-07-13 10:14:58
Original
767 people have browsed it

Use the session_set_save_handler() function in php to save the session to the MySQL database instance, sessionhandler

PHP saves sessions by default in the form of files. This can only be used on Windows where the file space overhead is very small, but if we use the file system on uinx or liux, The file space overhead of such a file system is very large. However, sessions must be used all the time. A large number of users will create a lot of session files, which will bring performance problems to the entire server.

On the other hand, if the server adopts a cluster method, the consistency of the session cannot be maintained, so we are ready to use a database to save the session. In this way, no matter how many servers are used at the same time, just save their sessions Saving it on a database server can ensure the integrity of the session. Please read on for details on how to implement it.

By default, PHP saves sessions in file format. We can see this line in the PHP configuration file PHP.ini:

Copy code The code is as follows:

session.save_handler="files"

This means that the session is saved in a file. If we want to save it in a database, we need to change it to user mode and change it to
Copy code The code is as follows:

session.save_handler="use"

That's fine, but this just means that we don't use files to store sessions. We also need to select a database and create a database table.

To establish the database and the table structure of the database, we can use any database that PHP can use. Because the combination of PHP and mysql is the best, I will use mysql as an example. Of course, you can change the name to another database according to your needs.

Create database

Copy code The code is as follows:

create database 'session';

Create table structure
Copy code The code is as follows:

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

PHP save session and write PHP file
Copy code The code is as follows:

$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 it as session_user_start.php.

Now our PHP session saving work has been completed. As long as you include session_user_start.php when you need to use the session. Note that this file must be included in the first line of the file, and then like Just use the same method as the file session.

The above is just a simple tutorial. In actual applications, it can be packaged more professionally. The reference code is as follows:

SessionMysql.class.php

Copy code The code is as follows:

/**
* 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'), // Executed when running session_start()
array(&$this, 'close'), // Executed when the script execution is completed or session_write_close() or session_destroy() is called, that is, it will be executed after all session operations are completed
Array(&$this, 'read'), // Executed when running session_start(), because when session_start, the current session data will be read
Array(&$this, 'write'), // This method is executed when the script ends and session_write_close() is used to force the submission of SESSION data
array(&$this, 'destroy'), // Executed when running session_destroy()
Array(&$this, 'gc') // The execution probability is determined by the values ​​of session.gc_probability and session.gc_divisor. The timing is after open and read. Session_start will execute open, read and gc in succession
);
Session_start(); // This is also necessary. To open the session, it must be executed after session_set_save_handler
}
/**
  * session_set_save_handler open方法
  *
  * @param $savePath
  * @param $sessionName
  * @return true
 */
public function open($savePath, $sessionName) {
return true;
}
/**
  * session_set_save_handler close方法
  *
  * @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 the value of session_id
*
* @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['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 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!

Copy code The code is as follows:

new SessionMysql();

How to use database to implement PHP to save SESSION details??

I hope you can fully master this knowledge through the relevant methods and techniques introduced in this article. PHP $con =mysql_connection("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 ?

Session saving problem in PHP

PHP saves sessions by default in the form of files. This can only be used on Windows where the file space overhead is very small, but if we use the file system on uinx or liux, The file space overhead of such a file system is very large. However, sessions must be used all the time. A large number of users will create a lot of session files, which will bring performance problems to the entire server. On the other hand, if If the server adopts the cluster method, the consistency of the session cannot be maintained, so we are ready to use the database method to save the session. In this way, no matter how many servers are used at the same time, they only need to save their sessions on one database server. The integrity of the session can be saved. Please continue reading for details on how to implement it.
By default, PHP sessions are saved in the file format. We can see a line like this in the PHP configuration file php.ini, session.save_handler="files", which means using files. To save the session, if we want to use the database to save it, we need to change it to user mode and rename it session.save_handler="use". However, this only means that we do not use files to store sessions. We also need to Select the database and the tables to create the database.
To establish the database and the table structure of the database, we can use any database that PHP can use. Because the combination of PHP and MySQL is the best, I will use MySQL for the example. Of course, you can change the name to another database according to your needs. At the same time, because MySQL does not have transaction functions, it is faster than other databases. However, saving the session does not require transaction processing, so I think it is better here.
Create database, CREATE DATABASE 'session'; Create table structure CREATE TABLE 'session'( id CHAR(30) NOT NULL , 'user 'CHAR(30), data CHAR(3000) ,PARMIRY BY ('id') );
Write php file
$con =mysql_connection("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...The rest of the text>>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907278.htmlTechArticleThe session_set_save_handler() function is used in php to save the session to the MySQL database instance. The sessionhandler PHP saves the session by default. Saved as a file, this is only in the file...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template