Use session_set_save_handler () function will save the session to the MySQL database


widgets Article

Use session_set_save_handler () function will save the session to the MySQL database

PHP is the way to save the default session file used to save, which is only in the very small space overhead windows file can be used, but if we use uinx or the file system on liux when such files file system space overhead is great, but the session is to always use a large number of users would create a lot of session files, so bring the whole server performance issues.

On the other hand, if the server from the cluster by way of, then you can not maintain consistency session, so we are ready to adopt the way of a database to store session, so, regardless of several servers simultaneously, as long as they are kept in a session on the database server can guarantee the integrity of the session, specifically how to implement please read on.

In the case of default PHP session save file is used to preserve the way, we can see this line in the configuration file PHP.ini in PHP,

session.save_handler="files"

This means that the use of the file to save the session, to be used to store the database, then we need to change to user mode, change

session.save_handler="use"

On it, but this is just the way that I did not use the door to store session files, we have to select the database and the establishment of a database table.

Establishment of a database and table structure of the database, we can use any database PHP can be used, because the best combination of PHP and mysql, mysql do I use the example, of course, need to be renamed according to your other databases.

Create a database

create database 'session';

Create a table structure

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

PHP to write PHP files saved session

<?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 becoming session_user_start.php.

Now we save the PHP session work has been completed, as long as you need when using the session, the session_user_start.php included. Note that this file must be included in the first line of the file , and then use the file as session using the same method on it.

 


 

These are just a simple tutorial, in practical applications, it may be more professional package more, the following reference code:

SessionMysql.class.php

<?php
/**
 * SessionMysql database storage class
 */

defined('IN_QIAN') or exit('Access Denied');

class SessionMysql {

	public $ lifetime = 1800; // period, unit: second (S), 30 minutes by default
	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'), // runtime execution session_start (time)
			array (& $ this, 'close'), // will be executed when script execution is completed or call session_write_close () or session_destroy (), that is being implemented in all session after operation
			array (& $ this, 'read'), // executed at run session_start (time), because when session_start, go read the current session data
			array (& $ this, 'write') executed, // This method SESSION submit data script ends and force the use session_write_close ()
			array (& $ this, 'destroy'), // operation performed in the session_destroy (time)
			array (& $ this, 'gc') // execution probability is determined by the value session.gc_probability and session.gc_divisor, timing is open, then read, session_start would have been open, read, and gc
		);
		session_start (); // this is necessary to open the session, it must be performed in the back 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'] : '';
	}

	/**
	 * The value written 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 period (unit: seconds)
	 * @return bool
	*/
	public function gc($lifetime) {
		$expireTime = SYS_TIME - $lifetime;
		return $this->db->delete("`last_visit`<$expireTime");
	}
}
?>

Somewhere in the system files, you can instantiate this class! ! !

new SessionMysql();

 

Further reading: how PHP will save the session to the memcached?


widgets Related Articles

widgets Contribution

This article is contributed by CNB and text available under CC-SA-4.0