跟踪用户登录的时间

use*_*833 3 html php cookies time session

我目前正在尝试弄清楚如何计算用户登录我的网站的时间,然后显示时间。

本质上,当用户登录时,我需要一种方法来记录他们登录的时间,然后在我网站的另一个页面上,我想向他们显示他们登录了多长时间。我将如何去做呢使用 cookie 或会话变量?

小智 6

我会将他们登录的时间存储为会话变量,例如

$_SESSION['loginTime'] = new DateTime(date('y-m-d h:m:s'));
Run Code Online (Sandbox Code Playgroud)

然后用 计算差值diff

获取当前时间

$difference= $_SESSION['loginTime']->diff(new DateTime(date('y-m-d h:m:s')));
Run Code Online (Sandbox Code Playgroud)

然后你可以使用这些方法输出时间

echo $difference->y; //return the difference in Year(s).
echo $difference->m; //return the difference in Month(s).
echo $difference->d; //return the difference in Day(s).
echo $difference->h; //return the difference in Hour(s).
echo $difference->i; //return the difference in Minute(s)
echo $difference->s; //return the difference in Second(s). 
Run Code Online (Sandbox Code Playgroud)