php session操作类(附实例)

发布时间:2019-12-18编辑:脚本学堂
分享一个php session操作类,及具体的调用示例,有需要的朋友参考下。

一个不错的php session类,将session保存在数据库中,供大家参考。

1,php session类

<?php 
/*
* session类
* by www.jb200.com
 */  
class Session {
    //构造函数
    public function __construct(){ 
        session_set_save_handler(array(&$this, 'open'),array(&$this, 'close'),array(&$this, 'read'),array(&$this, 'write'),
array(&$this, 'destroy'),array(&$this, 'clean')); 
        session_start(); 
    } 

    //打开数据库连接
    public function open() { 
        $this->mysql = mysql_connect('localhost', 'root', 'mysql'); 
        $bSeldb = mysql_select_db('sudhir', $this->mysql); 
        if (!$bSeldb) { 
            die ('Can't use Database : ' . mysql_error()); 
        } 

    }
    
    //写session
    public function write($id, $data) { 
        $access = time(); 
        $id = mysql_real_escape_string($id); 
        $access = mysql_real_escape_string($access); 
        $data = mysql_real_escape_string($data); 
        $sql = "REPLACE INTO sessions VALUES  ('$id', '$access', '$data')"; 
        return mysql_query($sql, $this->mysql) or die(mysql_error()); 
    } 

    //读session
    public function read($id) { 
        $id = mysql_real_escape_string($id); 
        $sql = "SELECT data FROM   sessions WHERE  id = '$id'"; 
        if ($result = mysql_query($sql, $this->mysql)) { 
            if (mysql_num_rows($result)) { 
                $record = mysql_fetch_assoc($result); 
                return $record['data']; 
            } 
        } 
        return ''; 
    }

    //销毁session
    public function destroy($id) { 
        $id = mysql_real_escape_string($id); 
        $sql = "DELETE FROM   sessions WHERE  id = '$id'"; 
        return mysql_query($sql, $this->mysql); 
    }

    //清除session
    public function clean($max) { 
        $old = time() - $max; 
        $old = mysql_real_escape_string($old); 
        $sql = "DELETE FROM   sessions WHERE  access < '$old'"; 
        return mysql_query($sql, $this->mysql); 
    } 

    //关闭数据库连接
    public function close() { 
        mysql_close($this->mysql); 
    } 
} 
?>

2,调用示例:

<?php
//调用session类
require_once "session.php";

$oSession = new Session(); 
print_r($_SESSION); // First 
$_SESSION['hi'] = "脚本学堂"; // Comment this Once sessoin is set 
$_SESSION['test'] = "www.jb200.com"; // Comment this Once sessoin is set 
?>