首页 > 开发 > PHP > 正文

使用数据库保存session的方法

2024-05-04 23:00:50
字体:
来源:转载
供稿:网友
php的session默认是以文件方式保存在服务器端,并且在客户端使用cookie保存变量,这就会出现一个问题,当一个用户由于某种安全原因关闭了浏览器的cookie,程序中的session相关操作将无法执行。因此,如果能以数据库保存session数据,将不受客户端设置的限制,并且在性能和扩展性等方面有一个飞跃。程序中使用关键函数是session_set_save_handler,同时要将php.ini里的session.save_handler = files 改为 user。这里我们讨论的环境是linux(freesd)+apache+mysql+php。

数据表结构:[sessions]
create table sessions (  
sesskey char(32) not null,  
expiry int(11) unsigned not null,  
value text not null,  
primary key (sesskey)  
);

程序代码:[session_inc.php]
<?php
$sess_dbhost = "yourhost"; /* database server hostname */
$sess_dbname = "yourdb"; /* database name */
$sess_dbuser = "youruser"; /* database user */
$sess_dbpass = "yourpassword"; /* database password */

$sess_dbh = "";
$sess_life = get_cfg_var("session.gc_maxlifetime");

function sess_open($save_path, $session_name) {
    global $sess_dbhost, $sess_dbname, $sess_dbuser, $sess_dbpass, $sess_dbh;

    if (! $sess_dbh = mysql_pconnect($sess_dbhost, $sess_dbuser, $sess_dbpass)) {
        echo "<li>can't connect to $sess_dbhost as $sess_dbuser";
        echo "<li>mysql error: " . mysql_error();
        die;
    }

    if (! mysql_select_db($sess_dbname, $sess_dbh)) {
        echo "<li>unable to select database $sess_dbname";
        die;
    }

    return true;
}

function sess_close() {
    return true;
}

function sess_read($key) {
    global $sess_dbh, $sess_life;

    $qry = "select value from session_tbl 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 = addslashes($val);

    $qry = "insert into session_tbl values ('$key', $expiry, '$value')";
    $qid = mysql_query($qry, $sess_dbh);

    if (! $qid) {
        $qry = "update session_tbl 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 session_tbl where sesskey = '$key'";
    $qid = mysql_query($qry, $sess_dbh);

    return $qid;
}

function sess_gc($maxlifetime) {
    global $sess_dbh;

    $qry = "delete from session_tbl where expiry < " . time();
    $qid = mysql_query($qry, $sess_dbh);

    return mysql_affected_rows($sess_dbh);
}

session_set_save_handler(
"sess_open",
"sess_close",
"sess_read",
"sess_write",
"sess_destroy",
"sess_gc");

session_start();
?>

完成以上步骤后,在程序中使用require("session_inc.php")来代替session_start()即可,其他的session函数还是象以前一样的方法调用。



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表