doushao8399 2017-08-11 18:04
浏览 49
已采纳

强制在每个新的浏览器会话中登录用户?

I want to logout user if browser is closed and force it to login again on turning the browser on.

if (!(isset($_SESSION['admin']))) {
    header ('Location: login.php');
}

This doesn't work - because turning off the browser does not mean drop the sessions on server - if I understand well a lot of posts on SO and outside.

Using javascript to delete sessions just before closing the browser often doesn't work because browser will not wait to execute any code if user clicks to close the browser.

Second option is keeping server session alive by sending a js code from client (setInterval - ajax).

Problem here is scenario with multiple pages open on different tabs/windows, i.e. interference between multiple setInterval functions.

I also tried this:

session_set_cookie_params(0);
session_start();

This also doesn't work - after turning off/on the browser index.php is open without redirecting to login.php.

The reason is maybe browser option to automatically restore previously loaded pages.

So, what to do ?

  • 写回答

3条回答 默认 最新

  • douzhanlai4671 2017-08-11 19:17
    关注

    @Axalix wrote:

    If session relies on cookies, you just need to keep expiry date empty, then when browser / tab is closed this cookie will be removed from a browser automatically. That's a standard browsers behavior. Yes, the server will still keep it, but since browser doesn't have it, user will need to relogin

    You responded:

    could that be a possible security issue because cookies are javascript stuff - chengable by client?

    Yes cookies can be changed by the client but Axalix' answer from the comments is still the best if you intend to use $_SESSION. If you want to end session on browser exit so that a 2nd user doesn't come later and take over the old session, then you must trust the owner of the session with the session cookie.

    If you really want to break access as soon as the client leaves, then $_SESSION is not the best tool to track login state. Instead you could use WebSockets. The socket remains open as long as the webpage is open. Once the socket closes, you can invalidate any login state.

    This may be more trouble than it's worth though, so think hard about whether it is really that important. As an alternative, you could use SessionStorage, which is destroyed when the browser closes but it's also available to the user (so a user could just copy and save what's in SessionStorage, then recreate it later).

    Basically you need to trust the user who provided you the username and password.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来