把Session放入MySql

來源:互聯網
上載者:User
mysql|session session通常放在/tmp目錄下,而該檔案夾的許可權是everbody可讀,這個就非常可怕了!學校的論壇曾經就有人通過session來盜取帳號!所以後來就嘗試把session放入資料庫,表的結構和過程如下:
//建立表
//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的資料庫路徑,當某個頁面需要使用//session時,可以include這個部分,使用方法為:
<?
include "XX.php";//XX.php
session_start();
//以下就可以正常使用session了
?>

/******************************************************/
  XX.php 內容:
/*****************************************************/
<?
$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("不能串連資料庫!");
  $sess_dbh=mysql_pconnect('localhost','test','test') or die("不能串連資料庫!");

  // mysql_select_db("$dbname") or die("不能選擇資料庫!");
mysql_select_db('test') or die("不能選擇資料庫!");
  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");

?>

這樣一來,安全多了......

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.