作者:(無敵鐵金剛 Robins)

使用的資料庫MySQL來存取session。
首先要建立用來儲存session的資料表,指令如下:
CREATE TABLE sessions (session_id varchar(60),session_data text,session_lastused integer unsigned);

   以下程式碼直接帶過,關於詳細內容不多述,因為不包含在本文篇幅內:

 /****************************************************************************
 *                               變數設定                                    *
 ****************************************************************************/
 $host="";       //MySQL主機位置                                             *
 $account="";        //MySQL使用者帳號                                       *
 $password="";        //MySQL使用者密碼                                      *
 $db="";         //MySQL使用者的資料庫                                       *
 /***************************************************************************/
 function open($save_path,$session_name)
 {
     global $sess_save_path,$sess_session_name;
     $sess_save_path = $save_path;
     $sess_session_name = $session_name;
     return true;
 }

 function close()
 {
     return true;
 }
 function read($session_id)
 {
     global $host,$account,$db,$password;
     $link = mysql_connect($host,$account,$password);
     mysql_select_db($db);
     $result=mysql_query("select * from sessions
where session_id='$session_id'",$link);
     $numrows=mysql_num_rows($result);      //如果沒有該資料,傳回""
     if(!$numrows)
           return "";

     $row = mysql_fetch_array($result);
     extract($row);       //將資料從陣列中脫出
     return $session_data;
 }

 function write($session_id,$session_data)
 {
     global $host,$account,$db,$password;
     $link = mysql_connect($host,$account,$password);
     mysql_select_db($db);
     $result=mysql_query("select * from sessions
where session_id='$session_id'",$link);
     $numrows=mysql_num_rows($result);    //如果沒有資料,建立!;有資料,覆寫!
     if(!$numrows)
     {
         mysql_query("insert into sessions set session_id='$session_id',
session_data='$session_data',session_lastused='".time()."'",$link);
         return true;
     }
     mysql_query("update sessions set session_data='$session_data',
session_lastused='".time()."'where session_id='$session_id'",$link);
     return true;
 }

 function destroy($session_id)
 {
     global $host,$account,$db,$password;
     $link = mysql_connect($host,$account,$password);
     mysql_select_db($db);
     mysql_query("delete form sessions where session_id='$session_id'",$link);
     return true;
 }

 function gc($max_lifetime)
 {
     global $host,$account,$db,$password;
     $current=time();
     $max_lifetime=300;
     $limit=$current - $max_lifetime;
     $link = mysql_connect($host,$account,$password);
     mysql_select_db($db);
     mysql_query("delete from sessions where session_lastused < $limit",$link);
     return true;
 }

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



 以上就是完整的session資料存取用MySQL的六個函式,在最後還加上設定使用的函
 式,只要把上面存成一個檔案,以後始用只需要引入就好。
 
arrow
arrow
    全站熱搜

    vfhhu 發表在 痞客邦 留言(0) 人氣()