在销毁之前保存会话数据?
是否可以在销毁会话数据之前将其保存用于数据库目的?
例如,我有来自会话的以下数据,
// start session
session_start();
// init session var
if (!isset($_SESSION['images'])) $_SESSION['images'] = array();
array
0 =>
array
'image_id' => int 1
'image_title' => string 'test 1' (length=6)
1 =>
array
'image_id' => int 2
'image_title' => string 'test 2' (length=6)
并且我想在会话被销毁或浏览器关闭时将其发送到数据库。
if(unset($_SESSION['images']))
{
// do something?
}
可行吗?
Is it possible to save the session data for database purposes before being destroyed?
For instance, I have the data below from a session,
// start session
session_start();
// init session var
if (!isset($_SESSION['images'])) $_SESSION['images'] = array();
array
0 =>
array
'image_id' => int 1
'image_title' => string 'test 1' (length=6)
1 =>
array
'image_id' => int 2
'image_title' => string 'test 2' (length=6)
And I want to send it to database when the session is destroyed or when the browser is closed.
if(unset($_SESSION['images']))
{
// do something?
}
Is it feasible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该将
session_start();
视为在浏览器上创建一个 cookie,其哈希值与服务器上的会话文件相匹配,服务器将在您的“会话”时将所有数据放入 $_SESSION 中处于活动状态,一旦您关闭浏览器,该 cookie 将从浏览器中丢弃,最终(由 cron 调用的清理)会话文件将从服务器中删除。如果您想存储一段时间或某个用户的持久数据,那么您应该将其存储在数据库、缓存文件、内存缓存等中。
You should think of
session_start();
as creating a single cookie on your browser with a hash that matches a session file on the server, the server will place any data into the $_SESSION whilst your "session" is active, once you close the browser that cookie is discarded from your browser, and eventually(a clean-up invoked by a cron) the session file is removed from the server.If you want to store persistent data for a time period or user then you should store it in the database, a cache file, memcache or such.
您可以使用 session_set_save_handler() 手动管理会话设置用户级会话存储功能。然后您可以通过 session_register_shutdown() 处理会话关闭。
这是对此功能的一个有趣的测试:http://www.rooftopsolutions.nl/blog/160
You can manually manage your sessions with session_set_save_handler() which sets user-level session storage functions. Then you can handle your session shutdown via session_register_shutdown().
Here is an interesting test of this capability: http://www.rooftopsolutions.nl/blog/160
查看客户会话处理程序 http://www .php.net/manual/en/function.session-set-save-handler.php
Take a look at custome session handlers at http://www.php.net/manual/en/function.session-set-save-handler.php
这不会按您的预期工作(在变量未设置时执行)。相反,它只会成功地取消设置您的会话变量并执行
// do some
部分。This does not work as intended by you (being executed when the variable is unset). Instead it will just sucessfully unset your session variable and execute the
// do something
part.