Home > Backend Development > PHP Tutorial > How to save session in php using MySQL, mysqlsession_PHP tutorial

How to save session in php using MySQL, mysqlsession_PHP tutorial

WBOY
Release: 2016-07-13 09:49:41
Original
815 people have browsed it

How php uses MySQL to save the session, mysqlsession

This article describes the method of php using MySQL to save the session. Share it with everyone for your reference. The specific analysis is as follows:

This function is generally available in many large systems, but to separate it for analysis, there is not much reliable information on the Internet. Here I compiled an article to share with you

Using MySQL to save sessions has many advantages over files:

1) Conducive to distributed systems, files can only be saved on one machine
2) It is beneficial to systems with a large number of visits. When using files, each session is saved in a file, and the directory will be very large, making it difficult to find the session file.

//////使用MySQL保存会话首先要创建session表:
<&#63;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 "成功新建数据库表!";
&#63;>
Copy after login
/////////MysqlSession 类如下:
<&#63;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); 
} 
}
&#63;>
//用法:在原来使用 session_start 的地方,替换成 $session = new MysqlSession () 
//注意:包含此程序前要打开数据库,主程序退出前不能关闭数据库,否则会出错。

Copy after login

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1019079.htmlTechArticlephp uses MySQL to save the session, mysqlsession This article describes the method of php using MySQL to save the session. Share it with everyone for your reference. The specific analysis is as follows: In...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template