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
Related
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 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.
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'm having trouble forcing sessions to restart in PHP. Here's the problem:
I can get my session id with session_id(), copy it, and add to the very top of my script:
session_id('the_session_id');
session_start();
And when I open a new browser, the session from the other browser is not carried over. What settings can I check?
Reason:
If you close the browser window and open it again, then at this moment a second session is started with a different ID, if the used web application has some session based authentication system the user has to login again. At the same time the user has to logout twice!
Solution:
This function will use a real cookie for the session ID and updates the expiration time with every script execution. The expiration is equal to the PHP directive "gc_maxlifetime" (default) or every custom value. So, put this function in your PHP file. We will need it.
<?php
// $expire = the time in seconds until a session have to expire
function start_session($expire = 0)
{
if ($expire == 0)
$expire = ini_get("session.gc_maxlifetime");
else
ini_set("session.gc_maxlifetime", $expire);
if (empty($_COOKIE['PHPSESSID']))
{
session_set_cookie_params($expire);
session_start();
}
else
{
session_start();
setcookie("PHPSESSID", session_id(), time() + $expire);
}
}
?>
Now, in the top of your page where you're issuing session_id('the_session_id'); and session_start();, remove those lines and start session with this code below:
To start a session with an expire time given by the php configuration
start_session();
To start a session that will expire in 1 hour:
start_session(3600);
I want my users to be logged out automatically after X minutes of inactivity. I also want to have all sessions destroyed.
How can this be done? How can I check for inactivity then perform a function to log them out???
I tired Michiels approach and got no where.
On investigation I saw that the if statement simply added the expiry period to the current time so the statement never fired.
This is my altered version:
set this when logging in user or loading a secure page:
$_SESSION['expire'] = time()+1*60;
And use this to see if the expiry time is less than current time (i.e we're past the expiry limit):
if(time() > $_SESSION['expire']){
$user -> logout();
}
You can set session time out limit like:
ini_set('session.gc_maxlifetime',30);
Here is the possible solution for you.
You could also do:
$_SESSION['loginTime'] = time();
On every page, and when the user is trying to navigate and he has been inactive for an twenty minutes you can log him out like this:
if($_SESSION['loginTime'] < time()+20*60){ logout(); }
Depending on how fast your server is and how many users you have, you can have it send a request to your server whenever a user does anything (navigates, clicks a button, whatever). From this request, update a SQL table with their last activity time.
Have a cron job run through the table at some regular interval and delete the sessions of the users that have been inactive for whatever your threshold is going to be.
If your server is slow or you have a lot of users, you can have this script run infrequently.
PHP's session mechanism already have a garbage collector based on the inactivity timeout. You have no worry about.
You can set the last active time by $_SESSION['lastactive'] = time() and update it every time when user navigates to a new page. Then you can have a function timeout() on every page .
function timeout()
{
$maxtime = 60*2; // Here , maxtime has been set to 2 minutes
if(isset($_SESSION['lastactive']) and (time() - $_SESSION['lastactive'] > $maxtime )) // subtracting current time from lastactive time and seeing if it exceeded timeout limit.
{
signout(); //logging out
}
if(isset($_SESSION['lastactive']) and (time() - $_SESSION['lastactive'] < $maxtime )) // subtracting current time from lastactive time and seeing if it exceeded timeout limit.
{
return 1; // timeout limit not exceeded
}
else
{
if(!isset($_SESSION['lastactive']))
{
$_SESSION['lastactive'] = time(); //if lastactive is not set
}
}
}
Use unset($_SESSION['NAME']); or session_destroy();. You could also change the value of the session.
To do this at a certain time, you would need to set a timestamp in the database, and then call it to check if it's beyond X minutes. Look at the link at the bottom.
I'd personally just use cookies and make them expire at a certain time, but whatever floats your boat.
If current time is more than 30 seconds past time X (from the database)
$(document).ready( function()
{
setTimeout(function() { CALL LOGOUT.PHP VIA AJAX }, 720000);
});
720000 means 12 minutes ( for illustration purpose )
put this script in your header and set ur own time of inactivity
you can set what time u want , it will be work like
if you set 5 minutes then when u login to system then it start count for 5 min. but if u click on any module this script will be reloaded , because when page turns then header is also reload when script is reload then it start count from 0 (initial), but if u cant access the system within 5 min. then it will load the logout.php and system will logs-out
this is how i do it :
//set timeout period in seconds
$idleTime= 60*2;
//check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout'])){
$session_life = time() - $_SESSION['timeout'];
if($session_life > $idleTime){
// your logout code here*
}
}
$_SESSION['timeout'] = time();
This makes $_SESSION['timeout'] reset every time a page is reloaded, i have this in an include file in the header of every sub page, works for me atleast.
The simplest way is this. Send the user to a log out page if they are not activating certain elements on your website
$secondsWait = 300; // these are seconds so it is 300s=5minutes
header("refresh:$secondsWait; logout.php");
contents for the redirect... logout.php, destroy any sessions and maybe also send a message alerting the user why they were logged out
<?php
session_start();
session_unset();
session_destroy();
?>