有没有办法在PHP中的会话之间切换?
我在php会话中存储了大量数据并且存在许多溢出问题,所以现在第一个解决方案是以某种方式细分会话数据.例:
//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'
Run Code Online (Sandbox Code Playgroud)
那可能吗?提前致谢...
小智 7
虽然我怀疑有一种更好的方法可以做你想做的事情 - 严格回答你的问题:是的 - 你可以切换会话.
诀窍是保存并关闭现有会话,然后识别新会话然后启动它.
例:
<?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";
?>
Run Code Online (Sandbox Code Playgroud)
最后 - 将所有内容整合到您想要的功能中:
<?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();
}
?>
Run Code Online (Sandbox Code Playgroud)
这应该够了吧.
注:这是至关重要的,你的会话ID是唯一的.如果不这样做,宝贵的用户数据将面临风险.
为了使生活更复杂,您还可以为切换到的每个会话更改会话处理程序(会话数据的存储方式).如果您正在与第三方代码或系统进行交互,您可能会发现它正在使用不同的会话处理程序,这可能会使事情变得混乱.在这种情况下,您还可以获取/设置会话保存处理程序,并在开始下一个会话之前更改它.