seesion的入库(mysql)操作,主要是修改seesion的读取与写入操作
主要是通过 bool session_set_save_handler(seesion_open,seesion_close,session_read,session_write,session_destory,session_gc);
依次对应的是开启seesion连接方式,关闭session,读取session,写拉seesion,销毁session,seesion的垃圾加收机制。
基本实例项目
1 <?php 2 /* 3 * 创建数据库 4 drop DATABASE if EXISTS session; 5 create DATABASE session CHARSET utf8; 6 use session; 7 drop TABLE if EXISTS session; 8 create table session ( 9 sess_id char(32) UNIQUE NOT NULL, 10 sess_info text, 11 sess_expire int not null default 0 12 )CHARSET utf8 ENGINE INNODB; 13 */ 14 //session入库 15 //1. 开启session 16 function sess_open(){ 17 //连接mysql 18 mysql_connect(‘localhost‘,‘root‘,‘root‘); 19 mysql_query(‘set names utf8‘); 20 mysql_query(‘use session‘); 21 //查看当前调用了什么方法 22 echo __FUNCTION__.‘<br/>‘; 23 } 24 //2. 关闭session 25 function sess_close(){ 26 //关闭mysql 27 mysql_close(); 28 echo __FUNCTION__.‘<br/>‘; 29 } 30 //3. 读取session 31 function sess_read($sess_id){ 32 //从数据库读取 33 //echo $sess_id; //这个sess_id,是系统自动生成的 34 //在读取数据的时候我们要过滤掉过期的数据 35 //通过当前时间与系统的session最大周期的差 36 $expire = time() - ini_get(‘seesion.gc_maxlifetime‘); 37 $sql = "select * from session where sess_id = ‘{$sess_id}‘ and sess_expire >= ‘{$expire}‘"; 38 $res = mysql_query($sql); 39 echo __FUNCTION__.‘<br/>‘; 40 //得到一个数组 41 if($sess = mysql_fetch_assoc($res)){ 42 return $sess[‘sess_info‘]; 43 } 44 } 45 // 4.写入操作 46 function sess_write($sess_id,$sess_info){ 47 //向数据库中写入session 48 //echo $sess_id.$sess_info; 49 $time = time(); 50 $sql = ‘replace into session values(‘{$sess_id}‘,‘{$sess_info}‘,‘{$time}‘)‘;//使用replace主是要因为要重复修改seesion,而sess_id又是UNIQUE 51 echo __FUNCTION__.‘<br>‘; 52 return mysql_query($sql); 53 } 54 //5. 销毁 55 function sess_destroy($sess_id){ 56 //删除数据库中信息 57 $sql = "delete from session where sess_id = ‘{$sess_id}‘"; 58 echo __FUNCTION__.‘<br>‘; 59 return mysql_query($sql); 60 } 61 //6.回收 62 function sess_gc(){ 63 //删除过期的数据 64 $expire = time()-ini_get(‘session.gc_maxlifetime‘); 65 $sql = "delete from session where sess_expire < ‘{$expire}‘"; 66 echo __FUNCTION__.‘<br/>‘; 67 } 68 //修改session机制 69 70 session_set_save_handler($sess_open,$sess_close,$sess_read,$sess_write,$sess_destroy,$sess_gc); 71 //启动session 72 session_start(); 73 //加入session数据 74 $_SESSION[‘name‘] = ‘张三‘; 75 $_SESSION[‘age‘] = ‘25‘; 76 //查看数据 77 //var_dump($_SESSION); 78 //删除session 79 //session_destroy();
时间: 2024-10-25 03:39:54