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

保存SESSION到SQLITE,

Jun 06, 2016 pm 07:38 PM
s session sqlite keep

保存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
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to save pictures without watermark in Xiaohongshu How to save pictures without watermark in Xiaohongshu How to save pictures without watermark in Xiaohongshu How to save pictures without watermark in Xiaohongshu Mar 22, 2024 pm 03:40 PM

Xiaohongshu has rich content that everyone can view freely here, so that you can use this software to relieve boredom every day and help yourself. In the process of using this software, you will sometimes see various beautiful things. Many people want to save pictures, but the saved pictures have watermarks, which is very influential. Everyone wants to know how to save pictures without watermarks here. The editor provides you with a method for those in need. Everyone can understand and use it immediately! 1. Click the &quot;...&quot; in the upper right corner of the picture to copy the link 2. Open the WeChat applet 3. Search the sweet potato library in the WeChat applet 4. Enter the sweet potato library and confirm to get the link 5. Get the picture and save it to the mobile phone album

How to download and save Douyin videos How to download and save Douyin videos Mar 29, 2024 pm 02:16 PM

1. Open the Douyin app, find the video you want to download and save, and click the [Share] button in the lower right corner. 2. In the pop-up window that appears, slide the function buttons in the second row to the right, find and click [Save Local]. 3. A new pop-up window will appear at this time, and the user can see the download progress of the video and wait for the download to complete. 4. After the download is completed, there will be a prompt of [Saved, please go to the album to view], so that the video just downloaded will be successfully saved to the user's mobile phone album.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Implementing user permissions and access control using PHP and SQLite Implementing user permissions and access control using PHP and SQLite Jul 29, 2023 pm 02:33 PM

Implementing user permissions and access control using PHP and SQLite In modern web applications, user permissions and access control are a very important part. With proper permissions management, you can ensure that only authorized users can access specific pages and functions. In this article, we will learn how to implement basic user permissions and access control using PHP and SQLite. First, we need to create a SQLite database to store information about users and their permissions. The following is the structure of a simple user table and permission table

PHP and SQLite: How to do data compression and encryption PHP and SQLite: How to do data compression and encryption Jul 29, 2023 am 08:36 AM

PHP and SQLite: How to Compress and Encrypt Data In many web applications, data security and storage space utilization are very important considerations. PHP and SQLite are two very widely used tools, and this article will introduce how to use them for data compression and encryption. SQLite is a lightweight embedded database engine that does not have a separate server process but interacts directly with applications. PHP is a popular server-side scripting language that is widely used to build dynamic

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

PHP and SQLite: How to deal with long connections and disconnection and reconnection PHP and SQLite: How to deal with long connections and disconnection and reconnection Jul 29, 2023 am 09:05 AM

PHP and SQLite: How to deal with long connections and disconnection and reconnection Introduction: In web development, PHP and SQLite are two commonly used technologies. However, long connections and disconnection and reconnection are some of the problems often encountered when using PHP and SQLite. This article will introduce how to handle the problems of long connections and disconnection and reconnection in PHP, and provide some example codes to help developers better understand and solve these problems. 1. Persistent connection problem When using PHP to connect to SQLite database, long connection (Persis

How to save the videos of the video account to the photo album? Method sharing How to save the videos of the video account to the photo album? Method sharing Mar 26, 2024 am 11:21 AM

Video account is a popular short video application that allows users to shoot, edit and share their own videos. However, sometimes we may want to save these amazing videos to our photo album so that we can always look back at them when needed. So, next I will share some methods to teach you how to save the video of the video account to the album. Videos can be saved through the built-in function of the Video Number application. Open the app and find the video you want to save. Click the options icon in the lower right corner of the video, a menu will pop up, select &quot;Save to Album&quot;. This will save the video to your phone's photo album. Method two is to save the video by taking a screenshot. This method is relatively straightforward, but the saved image will contain elements such as video control bars, which is not pure enough. you

See all articles