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

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:

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

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!

转载于:https://my.oschina.net/haozi3156666/blog/364149

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值