gpt4 book ai didi

php - 在 session 之间切换

转载 作者:行者123 更新时间:2023-12-03 18:38:37 25 4
gpt4 key购买 nike

有没有办法在php中的 session 之间切换?

我在 php session 中存储了大量数据并且有很多溢出问题,所以现在出现的第一个解决方案是以某种方式分割 session 数据。例子:

//Uses session sector 1

switch_to_session('sector1');
$_SESSION['data1'] = 'tons of data'; //store data

//Uses session sector 2

switch_to_session('sector2');
$_SESSION['data1'] = 'another data';

//Return to sector 1
switch_to_session('sector1');
echo $_SESSION['data1']; //prints: 'tons of data'

那可能吗?提前致谢...

最佳答案

虽然我怀疑有更好的方法来做你想做的任何事情 - 严格回答你的问题:是的 - 你可以切换 session 。

诀窍是保存并关闭您现有的 session ,然后识别您的新 session ,然后启动它。

例子:

<?php
session_start(); // start your first session
echo "My session ID is :".session_id();

$sess_id_1 = session_id(); // this is your current session ID
$sess_id_2 = $sess_id_1."_2"; // create a second session ID - you need this to identify the second session. NOTE : *must be **unique** *;

$_SESSION['somevar'] = "I am in session 1";
session_write_close(); // this closes and saves the data in session 1

session_id($sess_id_2); // identify that you want to go into the other session - this *must* come before the session_start
session_start(); // this will start your second session
echo "My session ID is :".session_id(); // this will be the session ID that you created (by appending the _2 onto the end of the original session ID

$_SESSION['somevar'] = "I am in session 2";
session_write_close(); // this closes and saves the data in session 2

session_id($sess_id_1); // heading back into session 1 by identifying the session I you want to use
session_start();

echo $_SESSION['somevar']; //will say "I am in session 1";
?>

最后 - 把它放在你想要的功能中:
<?php 
function switch_to_session($session_id) {
if (isset($_SESSION)) { // if there is already a session running
session_write_close(); // save and close it
}

session_id($session_id); // set the session ID
session_start();
}
?>

这应该够了吧。

注意: 至关重要的 确保您的 session ID 是唯一的。否则,宝贵的用户数据将面临风险。

为了让事情变得更复杂,您还可以为切换到的每个 session 更改 session 处理程序( session 数据的存储方式)。如果您正在与 3rd 方代码或系统交互,您可能会发现它使用了不同的 session 处理程序,这可能会混淆问题。在这种情况下,您还可以获取/设置 session 保存处理程序并在开始下一个 session 之前进行更改。

关于php - 在 session 之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22460559/

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