2010-06-01 67 views
7

如何使用php和mysql在數據庫表中使用會話?在php數據庫中設置會話

+1

你能給我們多一點信息嗎?你打算怎麼處理會議? – 2ndkauboy 2010-06-01 14:02:27

+2

您可能需要先在Google上進行搜索。 它會爲您提供的第一個鏈接之一是,例如: http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/ – nico 2010-06-01 14:10:59

+0

通常會話存儲在服務器中的臨時文件中。我想將會話存儲在數據庫表中。 – shin 2010-06-01 14:22:25

回答

18

您將需要創建一個對象,像這樣:

class SessionHandler 
{ 
    private static $lifetime = 0; 

    private function __construct() //object constructor 
    { 
     session_set_save_handler(
      array($this,'open'), 
      array($this,'close'), 
      array($this,'read'), 
      array($this,'write'), 
      array($this,'destroy'), 
      array($this,'gc') 
     ); 
    } 

    public function start($session_name = null) 
    { 
     session_start($session_name); //Start it here 
    } 

    public static function open() 
    { 
     //Connect to mysql, if already connected, check the connection state here. 

     return true; 
    } 

    public static function read($id) 
    { 
     //Get data from DB with id = $id; 
    } 

    public static function write($id, $data) 
    { 
     //insert data to DB, take note of serialize 
    } 

    public static function destroy($id) 
    { 
     //MySql delete sessions where ID = $id 
    } 

    public static function gc() 
    { 
     return true; 
    } 
    public static function close() 
    { 
     return true; 
    } 
    public function __destruct() 
    { 
     session_write_close(); 
    } 
} 

然後在session_start前啓動這一課!

include 'classes/sessionHandlerDB.php'; 

$session = new SessionHandler(); 

$session->start('userbase'); 

$_SESSION['name'] = 'Robert Pitt'; //This is sent to SessionHandler::write('my_id','Robert Pitt') 
echo $_SESSION['name']; //This calls SessionHandler::read($id)//$id is Unique Identifier for that 

http://php.net/manual/en/function.session-set-save-handler.php

http://php.net/manual/en/function.serialize.php

+0

你能告訴我如何使用這段代碼來設置會話嗎?與正常的會話設置有什麼不同嗎? – shin 2010-06-01 14:20:36

+0

Bascially whaen您使用$ _SESSION ...這將查詢SessionHandler,這意味着會話處理程序是中間人,它存儲數據並返回數據,如果您應用自己的處理程序,您可以以任何方式存儲它,DB,文件等執行這將告訴PHP當你使用Session來查詢這個類的數據。只要你包含這個文件並創建它的一個實例,你所做的一切都不會改變,接受存儲方法將是DB。我更新了我的帖子,請回顧 – RobertPitt 2010-06-01 14:26:24

+0

此外,這段代碼是純粹的例子,我會擴展它有一個存儲對象,所以你減少了調用數據庫,也看看MemCached! – RobertPitt 2010-06-09 14:49:18