在php中在数据库中设置会话 [英] set session in database in php

查看:90
本文介绍了在php中在数据库中设置会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过php和mysql在数据库表中使用会话?

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

推荐答案

您将需要创建一个对象,如下所示:

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

然后在session_start之前初始化此类!

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

这篇关于在php中在数据库中设置会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆