把Session放入MySql
發(fā)表時間:2023-07-28 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]session通常放在/tmp目錄下,而該文件夾的權(quán)限是everbody可讀,這個就非?膳铝耍W(xué)校的論壇曾經(jīng)就有人通過session來盜取帳號!所以后來就嘗試把session放入數(shù)據(jù)庫,表的結(jié)構(gòu)和...
session通常放在/tmp目錄下,而該文件夾的權(quán)限是everbody可讀,這個就非?膳铝耍W(xué)校的論壇曾經(jīng)就有人通過session來盜取帳號!所以后來就嘗試把session放入數(shù)據(jù)庫,表的結(jié)構(gòu)和過程如下:
//創(chuàng)建表
//create sesslib.sql
CREATE TABLE sesslib (
data text,
time datetime,
id int(11) DEFAULT '0' NOT NULL auto_increment,
sid varchar(32) NOT NULL,
PRIMARY KEY (id),
UNIQUE sid (sid)
);
//End
//XX.php自定義了session的數(shù)據(jù)庫路徑,當(dāng)某個頁面需要使用//session時,可以include這個部分,使用方法為:
<?
include "XX.php";//XX.php
session_start();
//以下就可以正常使用session了
?>
/******************************************************/
XX.php 內(nèi)容:
/*****************************************************/
<?
$sess_dbh="";
$sess_maxlifetime=get_cfg_var("session.gc_maxlifetime");
function sess_open($save_path, $session_name) {
global $hostname, $dbusername, $dbpassword, $dbname, $sess_dbh;
//$sess_dbh=mysql_pconnect($hostname,$dbusername,$dbpassword) or die("不能連接數(shù)據(jù)庫!");
$sess_dbh=mysql_pconnect('localhost','test','test') or die("不能連接數(shù)據(jù)庫!");
// mysql_select_db("$dbname") or die("不能選擇數(shù)據(jù)庫!");
mysql_select_db('test') or die("不能選擇數(shù)據(jù)庫!");
return(true);
}
function sess_close() {
//mysql_close();
return(true);
}
function sess_read($sid) {
global $sess_dbh;
$result = mysql_query("select data from sesslib where sid='$sid'", $sess_dbh);
$n=mysql_num_rows($result);
if($n==0) {
return("");
}
else {
$sess_data=mysql_result($result,0);
return($sess_data);
}
}
function sess_write($sid, $sess_data) {
global $sess_dbh;
if(!empty($sess_data)){
$r=mysql_query("insert into sesslib set sid='$sid',data='$sess_data',time=now()", $sess_dbh);
if(!$r) { // insertion failed, means the session is already there, update it
$r=mysql_query("update sesslib set sid='$sid', data='$sess_data', time=now() where sid='$sid'",$sess_dbh);
}
return $r;
}}
function sess_destroy($sid) {
global $sess_dbh;
$r=mysql_query("delete from sesslib where sid='$sid'", $sess_dbh);
return($r);
}
function sess_gc($maxlifetime) {
global $sess_dbh, $sess_maxlifetime;
$r=mysql_query("delete from sesslib where unix_timestamp(now())-unix_timestamp(time)>$sess_maxlifetime", $sess_dbh);
return mysql_affected_rows($sess_dbh);
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
?>
這樣一來,安全多了......