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

前端之家收集整理的这篇文章主要介绍了在php中设置数据库中的会话前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在PHPmysql数据库表中使用session?
你需要创建一个这样的对象:
class SessionHandler 
{ 
    private static $lifetime = 0; 

    private function __construct() //object constructor
    { 
       session_set_save_handler(
           array($this,'open'),array($this,'close'),'read'),'write'),'destroy'),'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

原文链接:https://www.f2er.com/php/136016.html

猜你在找的PHP相关文章