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?
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).
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.
Related
I'm currently storing a timestamp of the users last activity in my database in which if that hasn't been updated for 15 minutes (for testing doing 2 minutes) I want it to log the user out.
I have been trying different things but they all seem to log me out even though they shouldn't be.
Example of something I've tried
$Online = time() - 120;
if ($CheckOnline['lastaction'] < $Online){
header("Location: Logout.php");
session_destroy();
}
Am I going at this the wrong way.? If I do $Online < $CheckOnline['lastaction'] it keeps me logged in but never logs me out.
Thank you in advance!
Supposing the 'lastaction' is in epoch time format, this would be quite easy. You can check by the current time minus the last action time, that will give you the time in-between the actions. You can do something like this:
$maxTimeAllowed = 120; // 2 Mins
if ((time() - $CheckOnline['lastaction']) > $maxTimeAllowed){
session_start();
session_destroy();
header("Location: Logout.php");
}
I should also mention, in order for you to destory a session you must start it first, but I figure you would handle that logic either in your logout.php or on the page this will be run on, but i've included it just incase.
Another alternative is via javascript.
setTimeout(() => {
window.location = 'logout.php'
}, 120000) // 120000 because JS counts in milliseconds
That way, this will ensure that no matter what the user will be logged out in 2m, not just when they make another request.
Sidenote: If the date/time in your database is stored not as epoch time, it might be worth using strtotime() to convert them, as epoch time is much easier to work with.
I am trying to log a user out of my CMS after a set amount of time. By inactive I mean has not clicked the mouse or typed on there keyboard. So after 30 minutes of inactivity my log out function is ran.
There is already a log out function built in to the CMS I am using -
<?php
session_start();
if (isset($_SESSION['user_id'])){
$login = 1;
}else{
$login = 0;
}
function confirm_logged_in() {
if (!isset($_SESSION['user_id'])) {
//redirect
header("Location: /_cms/login.php?login=0");
}
}
function logout(){
$_SESSION = array();
if(isset($_COOKIE[session_name()])){
setcookie(session_name(), '', time()-4200, '/');
}
session_destroy();
}
?>
Someone else wrote this code and it works. However I don't know the exact time it takes to log out an inactive user. The preset time is - 4200. What I want to find out is how long that takes to logout and if I can change it to any time I want. Can anyone advise?
The -4200 is just to destroy the cookie. Cookies are destroyed by setting a time in the past for them. So setting 4200 seconds backwards is just as effective as 1 second backwards.
To logout users there are multiple methods. You can have a your own cookie set with the last active time (set the time every time the user visits a page). At the beginning of each script include a function which gets this cookie and checks the value which should contain the last active time. If this time is older than your allowed inactive time, then destroy this cookie and destroy your session as well, if not, then update the value to the current time.
Of course, you can also store inside the session itself the last active time, which is a much more efficient way removing the overhead of cookie transfer and management.
EDIT
Below is a minimal code to check for the last active time and logout the user:
function login(){
//check login username/pass etc...
$_SESSION['last_active_time'] = time();
}
function auth(){
if($_SESSION['last_active_time'] < (time() - 1800)){ //1800 is 30 minutes (time in seconds)
logout(); //destroy the session in the logout function
}
else{
$_SESSION['last_active_time'] = time();
}
//do some auth related things
}
That's the basic logic behind this. Of course you would need to implement other stuff you need along with security, checking, etc....
I will try to answer your question and have some questions too.
What CMS are you using? If you can name the CMS, we can provide detailed and accurate solution
Regarding your function logout() and about the setcookie and -4200, whenever you call the function logout, it is checking if there is any coockie set. If yes, then it is just setting the EXPIRY TIME to 4200 seconds ago ie 7 minutes ago from current time. ie. It invalidates the Coockie which is present at present.
Refer the link: http://php.net/manual/en/function.setcookie.php
Now, what you want is that after 30 mins of inactivity, user should be logged out. Your current code is not built for that. You should write the logic to keep checking the last active time and should invoke the logout function if it is more than 30 mins. Now the question is, how to do? Am just modifying your code a bit
if (isset($_SESSION['user_id'])){
$login = 1;
// If the user has performed action within 30 minutes
if($_SESSION['last_active_on'] > (time() - (30*60))){
$_SESSION['last_active_on'] = time(); // Re-set the current time as Last Active
}else{
// User has done some action after 30 minutes.
logout(); // Invoke the Logout functionality
}
}else{
$login = 0;
}
Remember: time() Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
You have not added your login function here. You should modify your login function and should add one more line in that as
$_SESSION['last_active_on'] = time();
One more thing. All this can happen only if the requests are sent to the server. For example: Assume at 4:00 PM, due to some action, there was a server call. Assume at 4:25 you are moving your mouse cursor or clicking anywhere on the page, but if it doesn't send any request to server, then it is considered as in-active itself. And at 4:35 PM if the user does something where the request is sent to server [Normal request or Ajax],
then as per the server, it is 35 mins inactive state, hence it will logout. Hope this answers your question.
You can even refer the SO question: User Inactivity Logout PHP It may also help you.
I need to ensure that a person has been to, and filled out, a registration form before going to the product download page. Right now I submit the form via ajax and if the returned JSON = success I redirect to the appropriate download page accordingly. I would like to protect the download page from direct access, to ensure we capture the lead first. I know that PHP sessions and cookies can be manipulated but it fits our needs, I am aware of the consequences etc and just need to make this work.
So on page 'http://www.example/register.php' I want to set and hash a cookie based on the current time:
<php
$time = ('Y-m-d H:i:s');
//set a new cookie with this value and hash it
?>
Then on http://www.example.com/download.php check for the cookie, if it is set AND set within the last hour display the download content, if it isn't set or has expired, redirect back to the register page
<php
if !$cookie or expred {
location('http://www.example.com/register.php');
die();
} else {
//download content
}
?>
I know this example is very rudementary, but I could use some help getting on the right path. I apprecite it!
You will need to use session_start() at the top of each page, without this you cannot read or write any session data.
Once you have done this, you will change session variables in the $_SESSION global. To set the time try $_SESSION['time'] = time(). This will save the current time in seconds (Unix Timestamp). To calculate if the time was set greater than an hour ago use this:
session_start();
// 60 seconds * 60 minutes = 3600, or 3600 = seconds in an hour
if(time() - $_SESSION['time'] > 3600) {
// Current time - survey_time is greater than one hour (expired)
header('Location: /survey/page/url/');
} else {
// Not expired - do stuff
}
Let me know if you have any questions!
I have a PHP app written in codeIgniter. Getting some complaints from clients about the app timing out. Their session times out after two hours of inactivity and they can't seem to remember that.
Is there a way and if so, how, to show a pop up message when a users session has timed out?
Thank you in advance.
PHP cannot display a pop up by itself, but you could probably have a JavaScript query the session status and display a pop up when the session is expired, or even better, count the time since the session opened and let the user know in advance that his session is about to time out
If you want change the duration of the session, see this line in your config.php
$config['sess_expiration'] = 7200;
7200 is 120 minutes * 60 seconds. If you change it to 0, the session will not expire.
To add a warning, the very simplest method would probably to add a JavaScript similar to
setTimeout(function(){alert("Your session will expire in 5 minutes")},6900000); // 6900 seconds (115 minutes) * 1000 milliseconds
You could do it using:
Javascript function using timers (and show a popup after a period of time)
In PHP using a timer set in your $_SESSION and calculate the difference in timestamps (when the user is redirected to a login page, pass a message "Your session has timed out")
A hard-timeout/page redirect using a meta equiv tag to a session-timeout page.
You can even go as far as offering different timeout periods for different user groups...
An example using PHP, which logs them out, tells them and redirects once they log back in:
// get time now
$now = time();
// Set session period
$autologout = '7200';
if (isset($_SESSION["TimeOut"]))
{
if ($now > $_SESSION["TimeOut"])
{
// Unregister session and set message
session_unregister("authenticatedUser");
session_register("loginMessage");
$loginMessage = "Your session has timed out";
// Capture request URL and store in a cookie so that they
// are logged back into the page they were requesting
$requestURL = $_SERVER[REQUEST_URI];
setcookie("requestURL",$requestURL,"0",'/','',FALSE,TRUE);
// Redirect back to login page
header("Location: " . $loginScript);
exit;
} else {
$_SESSION['TimeOut'] = ($now + $autologout);
}
} else {
$_SESSION['TimeOut'] = ($now + $autologout);
}
This presumes that your system session timeouts are longer or set otherwise. It's not written for codeIgnitor either, but hopefully helpful to understand what can be done to soften the blow of session expiry.
Probarly your session maxlifetime is 2 hours.
You can edit that with this: (replace 8 with the max lifetime in hours).
ini_set(’session.gc_maxlifetime’, 8*60*60);
I want the code snippet
echo "This is a test";
to be printed once every hour. So when the user loades index.php the first time it should be printed. When the user immediately after that reloads the page it should dissapear. After one hour it should be printed again...
How can I do this? Thanks.
This should work:
session_start();
if (!isset($_SESSION["last_shown"])) // If the session variable
// was never set
or ($_SESSION["last_shown"] < (time() - 3600)) // or was set more than
// 1 hour (3600 secs) ago
{
echo "This is a test"; // Make output
$_SESSION["last_shown"] = time(); // Update session variable
// with current time
}
Rather than sessions, set a cookie to expire in 1 hour. on page load, if the cookie is there don't display the message. The advantage over sessions is that the user can close the browser and return later (if you want that)
if (!isset($_COOKIE['sesslock']))
{
// No cookie - show message & set cookie (expires in 1 hour, 3600sec)
setcookie('sesslock','ok', time()+3600);
echo "this is a test";
}
else
{
// The cookie is there, don't display your message
}
you can set the current time to a $_SESSION variable and if the user changes the page check the session time variable.
and if that time is greater than one hour, than display the message