php使用MySQL保存session会话的方法,mysqlsession
php使用MySQL保存session会话的方法,mysqlsession
本文实例讲述了php使用MySQL保存session会话的方法。分享给大家供大家参考。具体分析如下:
在很多大的系统中一般都有这个功能,但是要分离出来分析,网上靠谱的资料也不太多 这里我整理了一篇发出来与大家分享
使用MySQL保存session会话较files有很多优点:
1) 有利于分布式系统,files只能保存在一台机器上
2) 有利于大访问量的系统,使用files时每个session保存在一个文件中,目录会超级大,查找session文件会比较困难。
//////使用MySQL保存会话首先要创建session表: <?php $hostname_login = "localhost"; // Server address $username_login = "root"; // User name $password_login = ""; // Password // $data_name = "session"; // Database name $login = mysql_pconnect($hostname_login, $username_login, $password_login) or trigger_error(mysql_error(),E_USER_ERROR); $sql="SHOW DATABASES LIKE '".$data_name."'"; // If it is exist if($rs_table=mysql_query($sql,$login)) { if($rs_value=mysql_fetch_array($rs_table)) { echo "数据库已经存在!\n!"; exit(); } } $sql="CREATE DATABASE $data_name"; mysql_query($sql); // Crate database echo "数据库创建成功!\n"; mysql_select_db($data_name, $login); $sql="CREATE TABLE `sessions` ( `SessionKey` varchar(32) NOT NULL default '', `SessionArray` blob NOT NULL, `SessionExpTime` int(20) unsigned NOT NULL default '0', PRIMARY KEY (`SessionKey`), KEY `SessionKey` (`SessionKey`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; //新建数据库 sql语句 mysql_query($sql); echo "成功新建数据库表!"; ?>
/////////MysqlSession 类如下: <?php class MysqlSession { // 注意在有使用Session的页面。页面一定要顶格,页面开始处不能留空。 private $DB_SERVER = "localhost"; // 数据库服务器主机名 private $DB_NAME = ""; // 数据库名字 private $DB_USER = "root"; // MYSQL 数据库访问用户名 private $DB_PASS = ""; // MYSQL 数据库访问密码 private $DB_SELECT_DB = ""; //private $SESS_LIFE = 1440; // Session的最大使用时长,单位秒。 private $SESS_LIFE = 0; function MysqlSession (&$sessionDB) { //session_write_close(); $this->DB_NAME = &$sessionDB; $this->SESS_LIFE = get_cfg_var("session.gc_maxlifetime"); session_module_name('user'); session_set_save_handler( array(&$this, 'sess_open'), array(&$this, 'sess_close'), array(&$this, 'sess_read'), array(&$this, 'sess_write'), array(&$this, 'sess_destroy'), array(&$this, 'sess_gc') ); session_start(); } function sess_open($save_path, $session_name){ // 打开数据库连接 if (! $this->DB_SELECT_DB = mysql_pconnect($this->DB_SERVER, $this->DB_USER, $this->DB_PASS)) { echo "SORRY! MYSQL ERROR : Can't connect to $this->DB_SERVER as $DB_USER"; echo "MySQL Error: ", mysql_error(); die; } if (! mysql_select_db($this->DB_NAME, $this->DB_SELECT_DB)) { echo "SORRY! MYSQL ERROR : Unable to select database $this->DB_NAME"; die; } return true; } function sess_close() { return true; } function sess_read($SessionKey){ $Query = "SELECT SessionArray FROM sessions WHERE SessionKey = '".$SessionKey."' AND SessionExpTime > " . time(); // 过期不读取。 $Result = mysql_query($Query, $this->DB_SELECT_DB); if (list($SessionArray) = mysql_fetch_row($Result)) { return $SessionArray; } return false; } function sess_write($SessionKey, $VArray) { $SessionExpTime = time() + $this->SESS_LIFE; // 更新Session过期时间, //Session过期时间 = 最后一次更新时间 + Session的最大使用时长 $SessionArray = addslashes($VArray); $Query = "INSERT INTO sessions (SessionKey,SessionExpTime,SessionArray) VALUES ('".$SessionKey."','".$SessionExpTime."','".$SessionArray."')"; $Result = mysql_query($Query, $this->DB_SELECT_DB); if (!$Result){ $Query = "UPDATE sessions SET SessionExpTime = '".$SessionExpTime."', SessionArray = '".$SessionArray."' WHERE SessionKey = '".$SessionKey."' AND SessionExpTime > " . time(); $Result = mysql_query($Query, $this->DB_SELECT_DB); } return $Result; } function sess_destroy($SessionKey) { $Query = "DELETE FROM sessions WHERE SessionKey = '".$SessionKey."'"; $Result = mysql_query($Query, $this->DB_SELECT_DB); return $Result; } function sess_gc($maxlifetime) { // 这个垃圾清除器系统调用。 //默认是1440秒清除一次。参数可以在PHP.ini里面设置。 $Query = "DELETE FROM sessions WHERE SessionExpTime < " . time(); $Result = mysql_query($Query, $this->DB_SELECT_DB); return mysql_affected_rows($this->DB_SELECT_DB); } } ?> //用法:在原来使用 session_start 的地方,替换成 $session = new MysqlSession () //注意:包含此程序前要打开数据库,主程序退出前不能关闭数据库,否则会出错。
希望本文所述对大家的php程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

CMS stands for Content Management System. It is a software application or platform that enables users to create, manage, and modify digital content without requiring advanced technical knowledge. CMS allows users to easily create and organize content

The page is blank after PHP connects to MySQL, and the reason why die() function fails. When learning the connection between PHP and MySQL database, you often encounter some confusing things...
