您的位置:首页 > 运维架构 > 网站架构

同一个浏览器打开多个标签访问同一个网站,只能等待其中一个执行完毕才能执行下一个(php的session锁机制)

2015-01-06 00:00 639 查看
Many people are aware that modern browsers limit the number of concurrent connections to a specific domain to between 4 or 6. This means that if your web page loads dozens of asset files (js, images, css) from the same domain they will be queued up to not exceed this limit. This same problem can happen, but even worse, when your page needs to make several requests to PHP scripts that use sessions.

Problem

PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.
The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.

Solution

The session file remains locked until the script completes or the session is manually closed. To prevent multiple PHP requests (that need $_SESSION data) from blocking, you can start the session and then close the session. This will unlock the session file and allow the remaining requests to continue running, even before the initial request has completed.
To close the session, call:

view source
print
?

1.

session_write_close();


This technique works great if you do not need to write to the session after your long-running process is complete. Fortunately, the $_SESSION data is still available to be read, but since the session is closed you may not write to it.

Example

view source
print
?

01.

<?php


02.

// start the session


03.

session_start();


04.


05.

// I can read/write to session


06.

$_SESSION
[
'latestRequestTime'
] =time();


07.


08.

// close the session


09.

session_write_close();


10.


11.

// now do my long-running code.


12.


13.

// still able to read from session, but not write


14.

$twitterId
=
$_SESSION
[
'twitterId'
];


15.


16.

// dang Twitter can be slow, good thing my other Ajax calls


17.

// aren't waiting for this to complete


18.

$twitterFeed
=fetchTwitterFeed(
$twitterId
);


19.


20.

echo
json_encode(
$twitterFeed
);


21.

?>


Be Sociable, Share!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  session session锁 php
相关文章推荐