Home > php教程 > php手册 > 保存SESSION到SQLITE,

保存SESSION到SQLITE,

WBOY
Release: 2016-06-06 19:38:12
Original
1495 people have browsed it

保存SESSION到SQLITE Save Session ThinkPHP ?php/** * Sqlite保存SESSION * @author WeakSun 52132522@qq.com */namespace Think\Session\Driver;use SessionHandlerInterface;use PDO;class Sqlite implements SessionHandlerInterface {static protected $

保存SESSION到SQLITE Save Session ThinkPHP
<?php
/**
 * Sqlite保存SESSION
 * @author WeakSun <52132522@qq.com>
 */
namespace Think\Session\Driver;

use SessionHandlerInterface;
use PDO;

class Sqlite implements SessionHandlerInterface {

	static protected $tableNameName, $expire, $handler, $nowTime;

	public function __construct() {
		empty(static::$expire) && static::$expire = C('SESSION_EXPIRE', null, false) ? C('SESSION_EXPIRE') : ini_get('session.gc_maxlifetime');
		empty(static::$nowTime) && static::$nowTime = isset($GLOBALS['_beginTime']) ? $GLOBALS['_beginTime'] : microtime(true);
		empty(static::$tableNameName) && static::$tableNameName = C('SESSION_TABLE') ? C('SESSION_TABLE') : 'iSession';
		$dbFile = TEMP_PATH . 'Caches.tmp';
		$isCreate = is_file($dbFile);
		if (empty(static::$handler)) {
			static::$handler = new PDO("sqlite:{$dbFile}", null, null, array(PDO::ATTR_PERSISTENT => true));
			empty($isCreate) && $this->exec("PRAGMA encoding = 'UTF8';PRAGMA temp_store = 2;PRAGMA auto_vacuum = 0;PRAGMA count_changes = 1;PRAGMA cache_size = 9000;");
			$this->chkTable() || $this->createTable();
		}
	}

	/**
	 * 创建SessionID
	 * @return string
	 */
	public function create_sid() {
		return uniqid(sprintf('%08x', mt_rand(0, 2147483647)));
	}

	/**
	 * 打开session
	 * @param string $path
	 * @param string $name
	 * @return boolean
	 */
	public function open($path, $name) {
		return is_object(static::$handler);
	}

	/**
	 * 关闭Session
	 * @return boolean
	 */
	public function close() {
		return true;
	}

	/**
	 * 读取Session
	 * @param string $id
	 * @return string
	 */
	public function read($id = null) {
		$table = static::$tableNameName;
		$sth = static::$handler->query("SELECT `value` FROM `{$table}` WHERE `id`='{$id}' AND `expire` > strftime('%s','now') LIMIT 1", PDO::FETCH_NUM);
		if (!empty($sth)) {
			list($data) = $sth->fetch();
			unset($sth);
		} else {
			$data = '';
		}
		return $data;
	}

	/**
	 * 写入Session
	 * @param string $id
	 * @param string $data
	 * @return integer
	 */
	public function write($id = null, $data = null) {
		$table = static::$tableNameName;
		$expire = ceil(static::$expire + static::$nowTime);
		return $this->exec("REPLACE INTO `{$table}` VALUES('{$id}','{$data}',{$expire})");
	}

	/**
	 * 销毁Session
	 * @param string $id
	 * @return integer
	 */
	public function destroy($id = 0) {
		$table = static::$tableNameName;
		return $this->exec("DELETE FROM `{$table}` WHERE `id` = '{$id}'");
	}

	/**
	 * 垃圾回收
	 * @param string $expire
	 * @return integer
	 */
	public function gc($expire = 0) {
		$table = static::$tableNameName;
		return $this->exec("DELETE FROM `{$table}` WHERE `expire` < strftime('%s','now');VACUUM;");
	}

	/**
	 * 检查当前表是否存在
	 * @return bool 返回检查结果,存在返回True,失败返回False
	 */
	protected function chkTable() {
		return in_array(static::$tableNameName, $this->getTables());
	}

	/**
	 * 获取当前数据库的数据表列表
	 * @return array 返回获取到的数据表列表数组
	 */
	protected function getTables() {
		$tables = $data = array();
		$sth = $this->query("SELECT `name` FROM `sqlite_master` WHERE `type` = 'table' UNION ALL SELECT `name` FROM `sqlite_temp_master`");
		if (!empty($sth)) {
			while ($row = $sth->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
				$tables[] = $row[0];
			}
			unset($sth, $row);
		}
		return $tables;
	}

	/**
	 * 创建当前数据表
	 * @return integer 成功返回1,失败返回0
	 */
	protected function createTable() {
		$tableName = static::$tableNameName;
		return $this->exec("CREATE TABLE IF NOT EXISTS `{$tableName}` (`id` VARCHAR PRIMARY KEY ON CONFLICT FAIL NOT NULL COLLATE 'NOCASE',`value` TEXT NOT NULL,`expire` INTEGER NOT NULL);");
	}

	public function __call($method, $arguments) {
		if (method_exists(self::$handler, $method)) {
			return call_user_func_array(array(self::$handler, $method), $arguments);
		} else {
			E(__CLASS__ . ':' . $method . L('_METHOD_NOT_EXIST_'));
			return;
		}
	}

}
Copy after login
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template