Table of Contents
PHP利用MySQL保存session的实现思路及示例代码,mysqlsession
怎做个会员登陆系统(用到php session但不用MySQL用TXT文件保存用户信息)
急PHP用户登录用mysql数据库存储session,并同时且用cookie存储的完整源程序或类
Home php教程 php手册 PHP利用MySQL保存session的实现思路及示例代码,mysqlsession

PHP利用MySQL保存session的实现思路及示例代码,mysqlsession

Jun 13, 2016 am 09:25 AM
mysql mysql database session

PHP利用MySQL保存session的实现思路及示例代码,mysqlsession

实现环境:

PHP 5.4.24
MySQL 5.6.19
OS X 10.9.4/Apache 2.2.26

一、代码

CREATE TABLE `session` (
`skey` char(32) CHARACTER SET ascii NOT NULL,
`data` text COLLATE utf8mb4_bin,
`expire` int(11) NOT NULL,
PRIMARY KEY (`skey`),
KEY `index_session_expire` (`expire`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
Copy after login

<&#63;php
/*
* 连接数据库所需的DNS、用户名、密码等,一般情况不会在代码中进行更改,
* 所以使用常量的形式,可以避免在函数中引用而需要global。
*/
define('SESSION_DNS', 'mysql:host=localhost;dbname=db;charset=utf8mb4');
define('SESSION_USR', 'usr');
define('SESSION_PWD', 'pwd');
define('SESSION_MAXLIFETIME', get_cfg_var('session.gc_maxlifetime'));

//创建PDO连接
//持久化连接可以提供更好的效率
function getConnection() {
try {
$conn = new PDO(SESSION_DNS, SESSION_USR, SESSION_PWD, array(
PDO::ATTR_PERSISTENT => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
));
return $conn;
} catch (Exception $ex) {

}
}

//自定义的session的open函数
function sessionMysqlOpen($savePath, $sessionName) {
return TRUE;
}

//自定义的session的close函数
function sessionMysqlClose() {
return TRUE;
}
/*
* 由于一般不会把用户提交的数据直接保存到session,所以普通情况不存在注入问题。
* 且处理session数据的SQL语句也不会多次使用。因此预处理功能的效益无法体现。
* 所以,实际工程中可以不必教条的使用预处理功能。
*/
/*
* sessionMysqlRead()函数中,首先通过SELECT count(*)来判断sessionID是否存在。
* 由于MySQL数据库提供SELECT对PDOStatement::rowCount()的支持,
* 因此,实际的工程中可以直接使用rowCount()进行判断。
*/
//自定义的session的read函数
//SQL语句中增加了“expire > time()”判断,用以避免读取过期的session。
function sessionMysqlRead($sessionId) {
try {
$dbh = getConnection();
$time = time();

$sql = 'SELECT count(*) AS `count` FROM session '
. 'WHERE skey = &#63; and expire > &#63;';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($sessionId, $time));
$data = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
if ($data = 0) {
return '';
}

$sql = 'SELECT `data` FROM `session` '
. 'WHERE `skey` = &#63; and `expire` > &#63;';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($sessionId, $time));
$data = $stmt->fetch(PDO::FETCH_ASSOC)['data'];
return $data;
} catch (Exception $e) {
return '';
}
}

//自定义的session的write函数
//expire字段存储的数据为当前时间+session生命期,当这个值小于time()时表明session失效。
function sessionMysqlWrite($sessionId, $data) {
try {
$dbh = getConnection();
$expire = time() + SESSION_MAXLIFETIME;

$sql = 'INSERT INTO `session` (`skey`, `data`, `expire`) '
. 'values (&#63;, &#63;, &#63;) '
. 'ON DUPLICATE KEY UPDATE data = &#63;, expire = &#63;';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($sessionId, $data, $expire, $data, $expire));
} catch (Exception $e) {
echo $e->getMessage();
}
}

//自定义的session的destroy函数
function sessionMysqlDestroy($sessionId) {
try {
$dbh = getConnection();

$sql = 'DELETE FROM `session` where skey = &#63;';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($sessionId));
return TRUE;
} catch (Exception $e) {
return FALSE;
}
}

//自定义的session的gc函数
function sessionMysqlGc($lifetime) {
try {
$dbh = getConnection();

$sql = 'DELETE FROM `session` WHERE expire < &#63;';
$stmt = $dbh->prepare($sql);
$stmt->execute(array(time()));
$dbh = NULL;
return TRUE;
} catch (Exception $e) {
return FALSE;
}
}

//自定义的session的session id设置函数
/*
* 由于在session_start()之前,SID和session_id()均无效,
* 故使用$_GET[session_name()]和$_COOKIE[session_name()]进行检测。
* 如果此两者均为空,则表明session尚未建立,需要为新session设置session id。
* 通过MySQL数据库获取uuid作为session id可以更好的避免session id碰撞。
*/
function sessionMysqlId() {
if (filter_input(INPUT_GET, session_name()) == '' and
filter_input(INPUT_COOKIE, session_name()) == '') {
try {
$dbh = getConnection();
$stmt = $dbh->query('SELECT uuid() AS uuid');
$data = $stmt->fetch(PDO::FETCH_ASSOC)['uuid'];
$data = str_replace('-', '', $data);
session_id($data);
return TRUE;
} catch (Exception $ex) {
return FALSE;
}

}
}

//session启动函数,包括了session_start()及其之前的所有步骤。
function startSession() {
session_set_save_handler(
'sessionMysqlOpen',
'sessionMysqlClose',
'sessionMysqlRead',
'sessionMysqlWrite',
'sessionMysqlDestroy',
'sessionMysqlGc');
register_shutdown_function('session_write_close');
sessionMysqlId();
session_start();
}
Copy after login

二、简介

使用MySQL保存session,需要保存三个关键性的数据:session id、session数据、session生命期。
考虑到session的使用方式,没必要使用InnoDB引擎,MyISAM引擎可以获得更好的性能。如果环境允许,可以尝试使用MEMORY引擎。
保存session数据的列,有需要的话,可以使用utf8或utf8mb4字符集;保存session id的列则没有必要,一般情况使用ascii字符集就可以了,可以节约存储成本。
保存session生命期的列,可以根据工程需要进行设计。比如datetime类型、timestamp类型、int类型。对于datetime、int类型可以保存session生成时间或过期时间。
如果有必要可以扩展session表的列并修改读、写函数以支持(维护)相关列来保存诸如用户名等信息。
当前版本,只要通过session_set_save_handler注册自定义的会话维护函数就可以,不需要在其之前使用session_module_name('user')函数。
当read函数获取数据并返回,PHP会自动对其进行反序列化,一般情况请不要对数据进行更改。
PHP传递给write函数的date参数是序列化之后的session数据,直接保存即可,一般情况请不要对数据进行更改。
按照本段代码的逻辑,PHP配置选项关于会话生命期的设置已经不再有效,这个值可以自行维护,不一定需要通过get_cfg_var获取。
sessionMysqlId()函数是为了避免大用户量、多台Web服务器情况下的碰撞,一般情况PHP自动生成的session id是可以满足用户要求的。
没了

三、需求

当用户量非常大,需要多台服务器提供应用的时候,使用MySQL存储会话相对使用会话文件具有一定的优越性。比如具有最小的存储开销,比如可以避免文件共享带来的复杂性,比如可以更好的避免发生碰撞,比如相比会话文件共享具有更好的性能。总体上来说,当访问量剧增的时候,如果使用数据库保存会话带来的问题是线性增长的,那么使用会话文件带来的问题几乎是爆炸性的。好吧,换一个更直白的说法吧:如果您的应用用户量不大,其实让PHP自己处理session就好了,没必要考虑MySQL。

怎做个会员登陆系统(用到php session但不用MySQL用TXT文件保存用户信息)

这个问题,可以用到数组存储,最后输出成分隔的字符串,是多字符串的操作。
我可以发一份示例代码给你。
 

急PHP用户登录用mysql数据库存储session,并同时且用cookie存储的完整源程序或类

$gb_DBname="charles_friend";//数据库名称
$gb_DBuser="charles_friend";//数据库用户名称
$gb_DBpass="wxyzoui";//数据库密码
$gb_DBHOSTname="localhost";//主机的名称或是IP地址
$SESS_DBH="";
$SESS_LIFE=get_cfg_var("session.gc_maxlifetime");//得到session的最大有效期。
function sess_open($save_path,$session_name){
global $gb_DBHOSTname,$gb_DBname,$gb_DBuser,$gb_DBpass,$SESS_DBH;
if(!$SESS_DBH=mysql_pconnect($gb_DBHOSTname,$gb_DBuser,$gb_DBpass)){
echo "

  • MySql Error:".mysql_error()."
  • ";
    die();
    }
    if(!mysql_select_db($gb_DBname,$SESS_DBH)){
    echo "
  • MySql Error:".mysql_error()."
  • ";
    die();
    }
    return true;
    }
    function sess_close(){
    return true;
    }
    function sess_read($key){
    global $SESS_DBH,$SESS_LIFE;
    $qry="select value from db_session where sesskey = '$key' and expiry > ".time();
    $qid=mysql_query($qry,$SESS_DBH);
    if(list($value)=mysql_fetch_row($qid)){
    return $value;
    }
    return false;
    }
    function sess_write($key,$val){
    global $SESS_DBH,$SESS_LIFE;
    $expiry=time()+$SESS_LIFE;
    $value=$val;
    $qry="insert into db_session values('$key',$expiry,'$value')";
    $qid=mysql_query($qry,$SESS_DBH);
    if(!$qid){
    $qry="update db_session set expiry=$expiry, value='$value' where sesskey='$key' and expiry >".time();
    $qid=mysql_query($qry,$SESS_DBH);
    }
    return $qid;
    } ......余下全文>>
     
  • 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)

    The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

    In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

    RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

    Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

    Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

    MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

    How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

    MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

    How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

    To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

    Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

    1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

    How to copy and paste mysql How to copy and paste mysql Apr 08, 2025 pm 07:18 PM

    Copy and paste in MySQL includes the following steps: select the data, copy with Ctrl C (Windows) or Cmd C (Mac); right-click at the target location, select Paste or use Ctrl V (Windows) or Cmd V (Mac); the copied data is inserted into the target location, or replace existing data (depending on whether the data already exists at the target location).

    How to view mysql How to view mysql Apr 08, 2025 pm 07:21 PM

    View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

    See all articles