简体   繁体   English

如何判断PHP会话是否超时

[英]How to tell if a PHP session has timed out

Currently I have been testing variables on $_SESSION, and if isset() returns false then assume the session has timed out to show a login page. 目前,我正在$ _SESSION上测试变量,如果isset()返回false,则假定会话已超时以显示登录页面。

session_start();

if (isset($_POST['login'])):
  // Process login credentials
  $_SESSION['account'] = Array('user'=>'username');
endif;

if (! isset($_SESSION['account'])):
  // User not logged in, show login page
else:
  // User is logged in, show account page
endif;

However a user has recently reported that the account page was blank. 但是,最近有用户报告该帐户页面为空白。 I assume no session data was available because my code above is flawed somehow. 我假设没有会话数据可用,因为上面的代码以某种方式存在缺陷。 Could someone point me in the right direction to correctly test if a session has timed out in PHP? 有人可以指出正确的方向来正确测试会话是否在PHP中超时吗?

if you could use: 如果可以使用:

if (! isset($_SESSION['account']) && !empty($_SESSION['account'])):
  // User not logged in, show login page
else:
  // User is logged in, show account page
endif;

so this wont pass for 2 conditions, 所以这不会通过两个条件,

  1. if session isn't set 如果未设置会话

  2. if session is set, but is blank! 如果设置了会话,但为空!

still a case exist of invalid values, for eg, username comes to xyz and you dont have any record matching xyz , then it could be a case of fetched no records and therefore it could be blank too! 仍然存在无效值的情况,例如,用户名进入xyz并且您没有与xyz匹配的记录,那么这可能是未获取任何记录的情况,因此也可能为空!

so more than just these statements, you should have a further check that if the data in $_POST matched to any of your records in the systems, and only after the match is confirmed, you should set this in to $_SESSION . 因此,除了这些语句之外,您还应该进一步检查$_POST的数据是否与系统中的任何记录匹配,并且只有在确认匹配之后,才应将其设置为$_SESSION

And these should cover most of your cases, making escapes lesser! 这些应该可以覆盖您的大多数情况,从而减少逃生!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM