輕鬆實現session的mysql處理 (轉)

worldblog發表於2007-12-11
輕鬆實現session的mysql處理 (轉)[@more@]

  通常,session都是儲存在臨時裡的,但是,要是把它儲存在裡,就會給我們帶來很多好處,比如統計線上人數之類的。廢話不說了,看:


include("_my.inc");

function open ($save_path, $session_name) {
  global $db,$REMOTE_ADDR;
  $db->query("delete from Sessions where SessionLast1 hour)");
  if($db->query(" * from Sessions where SessionID='".session_id()."'")
&& $arry=$db->fetch_array())
  $db->query("update Sessions set SessionLast=NOW() where
SessionID='".session_id()."'");
  else $db->query("insert into Sessions set
SessionID='".session_id()."',SessionName='$REMOTE_ADDR',SessionLast='NOW()'"
);
  return(true);
}

function close()

  return true;
}

function read ($id) {
  global $db;
  if(!$db->query("select SessionID from Sessions where SessionID='$id'")
|| $db->num_rows()<=0)return false;
  $SQL="select SessionData from Sessions where SessionID='$id'";
  $db->query($SQL);
  list($sess_data)=$db->fetch_row();
  return($sess_data);
}

function write ($id, $sess_data) {
  global $db;
  if(!$db->query("select SessionID from Sessions where SessionID='$id'") ||
$db->num_rows()<=0)return false;
  if($db->query("update Sessions set
SessionData='$sess_data',SessionLast=NOW() where SessionID='$id'"))
  return true;
  else return false;
}

function destroy ($id) {
  global $db;
  $db->query("delete from Sessions where SessionID='$id'");
}

function gc ($maxlifetime) {
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy","gc");

session_start();

?>
注:
資料表:Sessions
CREATE TABLE Sessions (
  SessionID varchar(50) NOT NULL,
  SessionName varchar(50) NOT NULL,
  SessionData blob,
  SessionLast datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  PRIMARY KEY (SessionID)
);


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-991441/,如需轉載,請註明出處,否則將追究法律責任。

相關文章