欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

将session存储到数据库中

程序员文章站 2022-03-30 20:08:08
...
Sql语句代码
CREATE TABLE sessions (  
  id CHAR(32) NOT NULL,  
  data TEXT,  
  last_accessed TIMESTAMP NOT NULL,  
  PRIMARY KEY (id)  
);

自定义会话处理代码

<?php  
/**  
 * Created by PhpStorm.  
 * User: michaeldu  
 * Date: 15/7/14  
 * Time: 下午2:57  
 */  
$sdbc = NULL;  
  
function open_session() {  
    global $sdbc;  
    $sdbc = mysqli_connect('192.168.31.172', 'root', 'root', 'phpadvanced');  
    return true;  
}  
  
function close_session() {  
    global $sdbc;  
    return mysqli_close($sdbc);  
}  
  
function read_session($sid) {  
    global $sdbc;  
    $q = sprintf('SELECT data FROM sessions WHERE  id="%s"', mysqli_real_escape_string($sdbc, $sid));  
    $r = mysqli_query($sdbc, $q);  
  
    if (mysqli_num_rows($r) == 1) {  
        list($data) = mysqli_fetch_array($r, MYSQLI_NUM);  
        return $data;  
    } else {  
        return '';  
    }  
}  
  
function write_session($sid, $data) {  
    global $sdbc;  
  
    $q = sprintf('REPLACE INTO sessions (id, data) VALUES ("%s", "%s")', mysqli_real_escape_string($sdbc, $sid), mysqli_real_escape_string($sdbc, $data));  
    $r = mysqli_query($sdbc, $q);  
    return true;  
}  
  
function destroy_session($sid) {  
    global $sdbc;  
    $q = sprintf('DELETE FROM session WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid));  
    $r = mysqli_query($sdbc, $q);  
  
    $_SESSION = array();  
  
    return true;  
}  
  
function clean_session($expire) {  
    global $sdbc;  
  
    $q = sprintf('DELETE FROM sessions WHERE DATE_ADD(last_accessed, INTERVAL %d SECOND) < NOW()', (int)$expire);  
    $r = mysqli_query($sdbc, $q);  
  
    return true;  
}  
  
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');  
  
session_start();

在普通页面调用代码

  
    
    
    colour_blue  
      
      
      
        
    
<?php  
if(empty($_SESSION)) {  
    $_SESSION['blah'] = 'umlaut';  
    $_SESSION['this'] = 3615684.45;  
    $_SESSION['that'] = 'blue';  
    echo 'Session已存储';  
} else {  
    echo 'SESSION已存在, '.print_r($_SESSION, 1).'';  
}  
  
if(isset($_GET['logout'])) {  
    session_destroy();  
    echo '会话结束';  
} else {  
    echo '登出';  
}  
  
echo '会话数据: '.print_r($_SESSION, 1).'';  
?>