如何使用php和mysql在數據庫表中使用會話?在php數據庫中設置會話
回答
您將需要創建一個對象,像這樣:
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
你能告訴我如何使用這段代碼來設置會話嗎?與正常的會話設置有什麼不同嗎? – shin 2010-06-01 14:20:36
Bascially whaen您使用$ _SESSION ...這將查詢SessionHandler,這意味着會話處理程序是中間人,它存儲數據並返回數據,如果您應用自己的處理程序,您可以以任何方式存儲它,DB,文件等執行這將告訴PHP當你使用Session來查詢這個類的數據。只要你包含這個文件並創建它的一個實例,你所做的一切都不會改變,接受存儲方法將是DB。我更新了我的帖子,請回顧 – RobertPitt 2010-06-01 14:26:24
此外,這段代碼是純粹的例子,我會擴展它有一個存儲對象,所以你減少了調用數據庫,也看看MemCached! – RobertPitt 2010-06-09 14:49:18
您可以通過session_handler
指令在php.ini
中對此進行控制。查看http://www.tonymarston.net/php-mysql/session-handler.html輕鬆步行(之前使用過)。
您需要使用session_set_save_handler
來編寫自定義打開,關閉,讀取,寫入,銷燬和垃圾回收函數。
見我的GitHub代碼片段PHP5.4-DB-Session-Handler-Class在PHP 5.4數據庫驅動的會話管理類。
- 1. 數據庫會話的區域設置
- 2. 設置SQL Server會話數據庫
- 3. PHP會話與數據庫會話
- 4. 未設置會話php
- 5. PHP YII2設置會話group_concat_max_len
- 6. Kohana中的數據庫和會話設置如何?
- 7. 會話VS實例VS數據庫中的Oracle NLS設置
- 8. PHP數據庫會話處理
- 9. PHP - 會話和數據庫問題
- 10. PHP - 與會話,Cookie或數據庫
- 11. 可以在php中設置會話設置
- 12. 在AngularJS中設置會話
- 13. springSecurityService和參數在會話中設置
- 14. 在jQuery中設置數組會話值
- 15. PHP - 將大會話數組存儲在$ _SESSION或數據庫中?
- 16. CodeIgniter設置用戶數據會話
- 17. 設置超過4KB的會話數據
- 18. JSP/Servlets會話+ PHP:跟蹤會話 - JSON /數據庫或HttpSessionListener?
- 19. 使用自定義會話ID處理PHP數據庫會話
- 20. PHP/PDO從會話變量數據庫中選擇數據
- 21. 在會話中保存數據庫值
- 22. Rails3.0.0Beta4將會話存儲設置爲數據庫
- 23. php store會話變量在mysql數據庫中
- 24. 何時使用數據庫將會話存儲在PHP中
- 25. 數據庫中總會話的數量與websphere中的連接池中設置的數據庫不相同
- 26. 設置HTTP頭(CI中)時,會丟失會話數據
- 27. 不能在會話codeigniter中設置用戶數據
- 28. 將MySQL設置結果存儲在PHP會話數組中以減少數據庫查找
- 29. 從數據庫到會話
- 30. Kohana 3.2 - 會話數據庫
你能給我們多一點信息嗎?你打算怎麼處理會議? – 2ndkauboy 2010-06-01 14:02:27
您可能需要先在Google上進行搜索。 它會爲您提供的第一個鏈接之一是,例如: http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/ – nico 2010-06-01 14:10:59
通常會話存儲在服務器中的臨時文件中。我想將會話存儲在數據庫表中。 – shin 2010-06-01 14:22:25