PHP并发会话和AJAX有问题

时间:2022-12-05 14:08:54

I have a session handler class that calls session_write_close() at the end of the script. This insures that even if a header() or exit() is issued the session data is saved.

我有一个会话处理程序类,在脚本末尾调用session_write_close()。这确保即使发出了header()或exit(),会话数据也被保存。

public function __destruct()
{
    session_write_close();
}

However, I have noticed that for one of my AJAX pages TWO session updates are committed by the database layer.

但是,我注意到,对于我的一个AJAX页面,数据库层提交了两个会话更新。

My guess is that the [1] page loads and sends an [2] AJAX request. That [2] AJAX request must start the session before the [1] page has a chance to call session_write_close().

我的猜测是[1]页面加载并发送一个[2]AJAX请求。[2] AJAX请求必须在[1]页面有机会调用session_write_close()之前启动会话。

After the [2] AJAX page has loaded the session then the [1] page finally saves the session and then shortly after the [2] AJAX request saves it's session - which overwrites the first one!

在[2]AJAX页面加载了会话之后,[1]页面最终保存了会话,然后在[2]AJAX请求保存了会话之后不久保存了会话——它覆盖了第一个会话!

It might look like this:

它可能是这样的:

[1] page loads session
[1] page sends output
[2] ajax loads session
[1] page saves session
[2] ajax sends output
[2] ajax saves session

What do I do to make sure one page isn't loading a session before another has a chance to save the session?

我要做什么才能确保一个页面没有加载一个会话,然后另一个页面才有机会保存会话?

1 个解决方案

#1


3  

The assumption was wrong.

这个假设是错误的。

...session data is locked to prevent concurrent writes only one script may operate on a session at any time http://us.php.net/session_write_close

…会话数据被锁定以防止并发写,在任何时候只有一个脚本可以在会话上操作http://us.php.net/session_write_close

In other words, you could be running 100 AJAX requests for a user at the same time and they would each wait their turn.

换句话说,您可以同时为一个用户运行100个AJAX请求,他们将各自等待轮到自己。

My problem turned out to be an error in selecting the right session table column resulting in my sessions being re-created each load.

我的问题是在选择正确的会话表列时出现了错误,导致每次加载都要重新创建会话。

#1


3  

The assumption was wrong.

这个假设是错误的。

...session data is locked to prevent concurrent writes only one script may operate on a session at any time http://us.php.net/session_write_close

…会话数据被锁定以防止并发写,在任何时候只有一个脚本可以在会话上操作http://us.php.net/session_write_close

In other words, you could be running 100 AJAX requests for a user at the same time and they would each wait their turn.

换句话说,您可以同时为一个用户运行100个AJAX请求,他们将各自等待轮到自己。

My problem turned out to be an error in selecting the right session table column resulting in my sessions being re-created each load.

我的问题是在选择正确的会话表列时出现了错误,导致每次加载都要重新创建会话。