set session in database in php

前端 未结 4 1018
北恋
北恋 2020-11-29 03:16

How can I use session in database table with php and mysql?

相关标签:
4条回答
  • 2020-11-29 03:34

    You control this in php.ini under the session_handler directive. Check out http://www.tonymarston.net/php-mysql/session-handler.html for a easy walk through (used it before).

    0 讨论(0)
  • 2020-11-29 03:36

    You would need to create an object like so:

    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();
        }
    }
    

    Then before session_start initiate this class!

    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 讨论(0)
  • 2020-11-29 03:36

    You'll need to usesession_set_save_handler to write custom open, close, read, write, destroy, and garbage collection functions.

    0 讨论(0)
  • 2020-11-29 03:43

    See my github code snippet PHP5.4-DB-Session-Handler-Class for a database driven session management class in PHP 5.4.

    0 讨论(0)
提交回复
热议问题