根据手册,我了解到当设置 php session 变量时,它被写入 session_save_path 文件夹中的文本文件。
我只是想知道这种情况是在解释器到达带有 session 变量的行时立即发生,还是在 PHP 解释器退出处理文件时发生(写入文本文件)?
例如,如果我要在连续的两行中设置和更新 session 变量(如我在下面给出的示例中所示),PHP 解释器是否会连续两次保存文件?
换句话说,哪些代码片段有正确的注释?
$_SESSION['my_variable']=1; // writes to the session text file
$_SESSION['my_variable']=2; // writes to the session text file again
die(); //
versus
$_SESSION['my_variable']=1; // updates the session file contents in the memory
$_SESSION['my_variable']=2; // updates the session file contents in the memory
die(); // writes to the session text file
最佳答案
如果出现以下情况,数据将写入文件:
- session_write_close() 被调用
- 脚本执行完毕
因此,只要您不执行 1),您的第二个假设就是正确的。
每次变量更改时都写入文件会非常昂贵,因为一般来说访问和写入磁盘很慢,因此 PHP 不会这样做。然而,应该注意的是,诸如 memcache 或 redis 之类的缓存系统将在发生更改时进行存储,因此当 PHP session 在可靠性方面不够时,依赖它们可能是个好主意。
关于PHP Session 的内部机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11454143/