如何防止已启动的 PHP 会话写入? [英] How to prevent a started PHP session from writing?
问题描述
我有一种情况,我已经开始了一个会话:
I have a situation where I've started a session with:
session_id( $consistent_session_name_for_user );
session_start();
$_SESSION['key'] = $value;
但后来我决定我实际上不想提交"(写)这个会话.PHP 似乎没有任何类型的 session_abort_write()
函数.我不想破坏先前脚本运行的会话变量,所以我不能使用 session_destroy()
but then later I decide I don't actually want to "commit" (write) this session. PHP doesn't seem to have any kind of session_abort_write()
function. I don't want to destroy the session variables from prior script runs, so I can't use session_destroy()
我尝试了 session_id("")
,但调用失败.我可以重定向"会话,以便它写入另一个会话,例如 session_id("trash")
,但这会导致大量 PHP (Apache) 连接尝试写入同一个会话文件",这是我想避免的.
I tried session_id("")
, but that call fails. I could "redirect" the session so it writes to another session, like session_id("trash")
, but that would cause a lot of PHP (Apache) connections to try to write to the same session "file", which I want to avoid.
我在这里高度简化了问题,我们实际上是在 Memcached 中存储会话,这是一个复杂的代码库.所以我不想一直向 Memcached 服务器发送不必要的垃圾"会话.
I'm highly simplifying the problem here, we're actually storing sessions in Memcached and this is a complex codebase. So I don't want to be sending unnecessary "trash" sessions to the Memcached server all the time.
推荐答案
我还没有真正确定这个方法是否会阻止将会话写入会话存储,但这是我最终使用的解决方案:
I haven't actually determined if this method prevents writing the session to the session store, but here's the solution I finally used:
session_id( 'trash' ); // or call session_regenerate_id() as someone else suggested
$_SESSION = array(); // clear the session variables for 'trash'.
我希望这有什么不会被写入的效果,但我猜它仍然会写入一个空白文件,因为 PHP 不知道 sess_trash 不存在.
I'm hoping this has the effect that nothing will get written, but I'm guessing it still will write a blank file, because PHP can't know that sess_trash isn't already there.
如果您想完全避免写入会话,则必须在 PHP 中使用自定义会话处理程序并设置全局标志以防止写入会话.
If you want to completely avoid writing the session, you'll have to use a custom session handler in PHP and set a global flag to prevent writing the session.
这篇关于如何防止已启动的 PHP 会话写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!