session通常放在/tmp目錄下,而該文件夾的權(quán)限是everbody可讀,這個(gè)就非常可怕了!學(xué)校的論壇曾經(jīng)就有人通過(guò)session來(lái)盜取帳號(hào)!所以后來(lái)就嘗試把session放入數(shù)據(jù)庫(kù),表的結(jié)構(gòu)和過(guò)程如下:
//創(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ù)庫(kù)路徑,當(dāng)某個(gè)頁(yè)面需要使用//session時(shí),可以include這個(gè)部分,使用方法為:
<?
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ù)庫(kù)!");
$sess_dbh=mysql_pconnect('localhost','test','test') or die("不能連接數(shù)據(jù)庫(kù)!");
// mysql_select_db("$dbname") or die("不能選擇數(shù)據(jù)庫(kù)!");
mysql_select_db('test') or die("不能選擇數(shù)據(jù)庫(kù)!");
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");
?>
這樣一來(lái),安全多了......