在php中设置数据库中的会话

时间:2010-06-01 13:57:45

标签: php

如何在php和mysql的数据库表中使用session?

4 个答案:

答案 0 :(得分:19)

你需要像这样创建一个对象:

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

答案 1 :(得分:1)

您可以在php.ini指令下的session_handler中对此进行控制。查看http://www.tonymarston.net/php-mysql/session-handler.html以便轻松浏览(之前使用过)。

答案 2 :(得分:1)

您需要使用session_set_save_handler来编写自定义打开,关闭,读取,写入,销毁和垃圾回收功能。

答案 3 :(得分:0)

请参阅我的github代码片段PHP5.4-DB-Session-Handler-Class,了解PHP 5.4中的数据库驱动的会话管理类。