-
- CREATE TABLE `db_session` (
- `sesskey` char(32) NOT NULL,
- `expiry` int(11) unsigned NOT NULL,
- `value` text NOT NULL,
- PRIMARY KEY (`sesskey`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-
复制代码
数据库表明:db_session
列名:sesskey,expiry,value 其中:sesskey为主键。
Value里面存放着session里面的值。
3.建立session_mysql.php文件。这个文件是用来构造保存session的方法的。修改一下参数直接使用就可以了。
session_mysql.php
php代码:
-
- $gb_DBname="db_myBBS";//数据库名称
- $gb_DBuser="root";//数据库用户名称
- $gb_DBpass="23928484";//数据库密码
- $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;
- }
- function sess_destroy($key){
- global $SESS_DBH;
- $qry="delete from db_session where sesskey = '$key'";
- $qid=mysql_query($qry,$SESS_DBH);
- return $qid;
- }
- function sess_gc($maxlifetime){
- global $SESS_DBH;
- $qry="delete from db_session where expiry < ".time();
- $qid=mysql_query($qry,$SESS_DBH);
- return mysql_affected_rows($SESS_DBH);
- }
- session_module_name();
- session_set_save_handler("sess_open","sess_close","sess_read","sess_write","sess_destroy","sess_gc");
- ?>
复制代码
4.建立测试文件。
在使用之前必须引用刚刚建立的session_mysql.php文件。
文件:session_test.php
-
- include ("session_mysql.php");
- session_start();
- $_SESSION['abc']= "A: I will be back!";
- $_SESSION['meto']= "B: Me too ";
- $_SESSION['name']= "louis ";
- echo "click me";
- ?>
复制代码
文件:get_session_test.php
-
- include ("session_mysql.php");
- session_start();
- echo $_SESSION['abc'];
- echo "
";
- echo $_SESSION['meto'];
- echo "
";
- echo $_SESSION['name'];
- $_SESSION['wq']="12e";
- echo "
click again";
- ?>
复制代码
文件:get_session_test2.php
-
- include ("session_mysql.php");
- session_start();
- echo $_SESSION['abc'];
- echo "
";
- echo $_SESSION['meto'];
- echo "
";
- echo $_SESSION['name'];
- echo "
";
- echo $_SESSION['wq'];
- //session_destroy();//用来销毁所有session的函数。
- ?>
复制代码
|