gpt4 book ai didi

php - 在php中的数据库中设置 session

转载 作者:可可西里 更新时间:2023-11-01 12:26:50 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于php - 在php中的数据库中设置 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2950355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com