Table of Contents
PHP实现利用MySQL保存session的方法,mysqlsession
怎做个会员登陆系统(用到php session但不用MySQL用TXT文件保存用户信息)
PHP中Session保存问题
Home php教程 php手册 PHP实现利用MySQL保存session的方法,mysqlsession

PHP实现利用MySQL保存session的方法,mysqlsession

Jun 13, 2016 am 09:26 AM
mysql php session

PHP实现利用MySQL保存session的方法,mysqlsession

session是PHP程序设计中服务器端用来保存用户信息的一个变量,具有非常广泛的应用价值。本文实例讲述了PHP实现利用MySQL保存session的方法。分享给大家供大家参考之用。具体步骤如下:

本文实例的实现环境为:

PHP 5.4.24
MySQL 5.6.19
OS X 10.9.4/Apache 2.2.26

一、代码部分

1.SQL语句:

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

2.PHP部分代码:

<&#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

二、简介

1.使用MySQL保存session,需要保存三个关键性的数据:session id、session数据、session生命期。

2.考虑到session的使用方式,没必要使用InnoDB引擎,MyISAM引擎可以获得更好的性能。如果环境允许,可以尝试使用MEMORY引擎。

3.保存session数据的列,有需要的话,可以使用utf8或utf8mb4字符集;保存session id的列则没有必要,一般情况使用ascii字符集就可以了,可以节约存储成本。

4.保存session生命期的列,可以根据工程需要进行设计。比如datetime类型、timestamp类型、int类型。对于datetime、int类型可以保存session生成时间或过期时间。

5.如果有必要可以扩展session表的列并修改读、写函数以支持(维护)相关列来保存诸如用户名等信息。

6.当前版本,只要通过session_set_save_handler注册自定义的会话维护函数就可以,不需要在其之前使用session_module_name('user')函数。

7.当read函数获取数据并返回,PHP会自动对其进行反序列化,一般情况请不要对数据进行更改。

8.PHP传递给write函数的date参数是序列化之后的session数据,直接保存即可,一般情况请不要对数据进行更改。

9.按照本段代码的逻辑,PHP配置选项关于会话生命期的设置已经不再有效,这个值可以自行维护,不一定需要通过get_cfg_var获取。

10.sessionMysqlId()函数是为了避免大用户量、多台Web服务器情况下的碰撞,一般情况PHP自动生成的session id是可以满足用户要求的。

三、需求

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

四、参考函数及概念部分:

1 http://cn2.php.net/manual/zh/function.session-set-save-handler.php
2 http://cn2.php.net/manual/zh/session.idpassing.php
3 http://cn2.php.net/manual/zh/pdo.connections.php
4 http://cn2.php.net/manual/zh/pdo.prepared-statements.php
5 http://dev.mysql.com/doc/refman/5.1/zh/sql-syntax.html#insert

希望本文所述实例对大家PHP程序设计有所帮助。

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

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

PHP中Session保存问题

php保存session 默认的是采用的文件的方式来保存的,这仅仅在文件的空间开销很小的windows上是可以采用的,但是如果我们采用uinx或者是liux上的文件系统的时候,这样的文件系统的文件空间开销是很大的,然而session是要时时刻刻的使用的,大量的用户就要创建很多的session文件,这样对整个的服务器带来性能问题,另一方面,如果服务器起采用群集的方式的话就不能保持session的一致性,所以我们就绪要采用数据库的方式来保存session,这样,不管有几台服务器同时使用,只要把他们的session保存在一台数据库服务器上就可以保存session的完整了,具体如何来实现请继续看下去。
  php的session默认的情况下是采用的文件方式来保存的,我们在php的配制文件php.ini中可以看到这样的一行,session.save_handler="files",这样的意思就是采用文件来保存session 的,要采用数据库来保存的话,我们需要修改成用户模式,改称 session.save_handler="use"就可以了,但是,这仅仅是说明我门没有采用文件的方式存储session,我们还要选择数据库和建立数据库的表。
  建立数据库和数据库的表结构,我们可以采用php可以使用的任何的数据库,因为php和mysql的结合最好,我就使用mysql来做事例,当然根据你的需要可以改称别的数据库,同时因为mysql没有事物的功能,这也比别的数据库更快,然而保存session 不需要事物处理的,在这里我觉得更好。
  创建数据库 , CREATE DATABASE 'session'; 创建表结构 CREATE TABLE 'session'( id CHAR(30) NOT NULL , 'user 'CHAR(30), data CHAR(3000) ,PARMIRY BY ('id') );
编写php文件
$con =mysql_connection("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......余下全文>>
 

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles