Domanda

I am currently trying to figure out how to time how long a user has been logged on my website, and then display the time.

Essentially, when the user logs in, I need a way to record the time they logged on, and then on another page of my site, I want to show them how long they've been logged in. How would I go about doing this using cookies or session variables?

È stato utile?

Soluzione

I would store the time they logged in as a session variable like

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

Then calculate the difference with diff.

Get the current time

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

Then you can output time since with these methods

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). 

Altri suggerimenti

Assuming you are using php you would set a session value with the current time, then retrieve the value from that session variable on the other page (where you show the time). On the login

session_start(); //immediately after <?php tag
$_SESSION ['timer'] = time();

and on the page you are retrieving it

session_start ();
$ timeSinceLogin =( time () - $_SESSION ['timer']) /60; //time in minutes. 

Don't forget that

session_start(); 

immediately after the php opening tag on every page you are using session data.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top