I want one session variable to be cleaned every 24 hours .I don't want to kill or unset all the sessions just one session to be unset every 24 hours a day.
When the session is 1st created on the client just give it a date:
if(!isset($_SESSION['date'])
$_SESSION['date'] = date('m_d_y');
Then whenever the page changes check that date:
if($_SESSION['date'] == date('m_d_y')){
//still today
}
else {
//destroy session
}
Or you could do it with timestamp and check based on the number of hours:
if(!isset($_SESSION['creationTime'])
$_SESSION['creationTime'] = time();
if (time() - $_SESSION['creationTime'] <= 60*60*24 ){
//still today
}
else {
//destroy session
}
try to set Cookie expired time into now() + 24 hours...
When you creating session, write to it timestamp. Then you are using seesion check the actually timestamp and of creating session, then if difference is grather than 86400, then drop session and create new one.
This solution prevent users from using sessions older than 24hours. You can apply other comparing algorithm to eg. prevent users from using session before 1AM of current day. Then will be work exaclly same when you will want erase session every 24hours in 1AM every day.
When create session (maybe when user login), declare session timeout:
session_start();
$_SESSION["timeout"] = time()+ (60*60*24);
Create backend function / page where jquery can call every 10 seconds / 5 seconds up to you (I save it as get_session.php):
session_start();
$session_life = time() - $_SESSION["timeout"];
$inactive = 0;
if($session_life > $inactive){
session_destroy();
echo 'Destroyed';
}
The jquery script run every 5 second (recommended at master page / template header / footer of the page):
<script type="text/javascript">
window.setInterval(function(){
sessionHeartBeat();
}, 5000);
function sessionHeartBeat(){
$.ajax({
url: 'get_session.php',
success: function(response){
console.log(response);
}
});
}
</script>
Related
I have a php webpage that logs users out after 10 seconds of inactivity. After 10 seconds, I need to hit the refresh button before it redirects to the main index.php page. How do I make a popup box displaying "You are logged out due to inactivity" and after that it redirects to index.php without refreshing?
P/S: I'm a student learning the basics so I don't know much.
session_start();
$timeout = 10;
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
// See if the number of seconds since the last
// visit is larger than the timeout period.
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
session_start();
}
}
So I tried something like this using alert.Why doesn't it work?
<?php
//include ("popup.php");
session_start();
$timeout = 10;
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
// See if the number of seconds since the last
// visit is larger than the timeout period.
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
echo"<script type='javascript'>alert('10 seconds over!');
header("location:../../index.php");
</script>";
}
// Destroy the session and restart it.
session_destroy();
session_start();
header("location:../../index.php");
}
// Update the timout field with the current time.
$_SESSION['timeout'] = time();
Implement a popup with Javascript; or
In your conditional, use header("Location: logout-notice.php");
Edit:
I can't test right now, but based on your update, the things I see is that you're checking for $_SESSION['timeout'] but I don't see it declared or given a value anywhere. You have the variable of $timeout set at the top but they're different variables.
Maybe something like this:
$_SESSION['timeout'] = time() + $timeout; // should = 1491838370 if set at UNIX time of 1491838360
if(time() > $_SESSION['timeout']){ // evaluated at 1491838380 which is > 1491838370 results in true
?>
<script type='javascript'>alert('10 seconds over!');</script>
<?php
header("Location: ../../index.php");
}
The question is where/how you'll be evaluating this. If you want each user's action to validate whether they've been active, you can include this script at the beginning of each file. The downside is that if they're inactive for a minute, it won't evaluate until they do something.
You could use a pure javascript version relying on SetInterval or SetTimeout to evaluate every ten seconds and pop up an alert with a window.location.href to index.php as well. Something like this (again you may need to tweak, this is untested):
var checkSession = setInterval(
function({
var sessionExpires = <?=$_SESSION['timeout']?>; //this is probably considered heresy, but as long as the javascript is evaluated by the PHP processor, it should work
var currentTime = Math.floor((new Date).getTime()/1000);
if(currentTime > sessionExpires ){
alert("Take your stuff and go!");
window.location.href = "../../index.php";
}
}, 10000);
I have to prepare a report in codeigniter of the login and logout time of users. I have overridden the session library and changed the function of set_userdata according to it.
My problem is when user doesn't select the logout button, or if he/she is logged in simultaneously from more then one system; in that case how can I keep a log of login and logout time?
I added the following code to the session_destroy function of the session library
$session_id=$this->userdata['session_id'];
$c_array=array('logout_time'=>date('Y-m-d H:i:s'));
$this->CI->db->where('session_id',$session_id);
$this->CI->db->update('login_activities',$c_array);
but the session_id changed after some time in the ci_session table
we cant always get the logout time, because if the user close the browser there won't be able to add a logout time, in the case of normal logout its ok..
here my suggession is:
instead of logout_time we need current_time and a usage field
if the user is logged an ajax is run on page for every second or (may be in 3 seconds or 5)
at every time the ajax runs: the current_time updated with the current time stamp, and the usage field must be updated with time in seconds that can be calculated by difference in login_time and current time
use the following function:
function getTimeInSec($t1, $t2)
{
$timeFirst = strtotime($t1);
$timeSecond = strtotime($t2);
$differenceInSeconds = $timeSecond - $timeFirst;
return $differenceInSeconds;
}
here $t1 is the current_time and $t2 is the login_time....
(both ar in format 'Y-m-d H:i:s')
script for ajax call:
<script>
jQuery(document).ready(function($){
getRefresh(1000);
});
function getHeader()
{
$.post("<?php echo site_url('mycontroller/refreshAjax');?>", {
},
function(response)
{
});
}
function getRefresh(tim)
{
getHeader();
setTimeout("getRefresh("+tim+")", tim);
}
</script>
in the controller function refreshAjax() there must be update query for the table to update...
i am looking for solution of my answer which is half completed i have to make the user logout from my website and i used your solution which is as follow:-
if( $_SESSION['last_activity'] < time()-$_SESSION['expire_time'] ) {
//have we expired?
//redirect to logout.php
header('Location: '.BASE_FULL_PATH.'/user/logout'); //change yoursite.com to the name of you site!!
} else{ //if we haven't expired:
$_SESSION['last_activity'] = time(); //this was the moment of last activity.
}
$_SESSION['logged_in'] = true;
$_SESSION['last_activity'] = time();
$_SESSION['expire_time'] = 24*60*60;
and it is working perfectly but i need to have an alert box when the session is about to expire.Try lot of stuff but doesn't help.Please reply and thanks for your brilliant demo
I know , this is not an efficient way, But you can try this.
try ajax, that runs a php file in server every 5 or 10 second time gap.
that ajax running php file contains session last_activity and expire_time comparing code,
<?php
$warning=100;
if( $_SESSION['last_activity']+warning < time()-$_SESSION['expire_time'] ) {
?>
<script type="text/javascript">
alert("Your session will expire soon!");
</script>
<?php
}
?>
You can set the variable $warning to adjust the alert message time.
Since your session expiry will reset every time you reload the page, then you can use the expiry time as the time argument of JavaScript's setTimeout() function.
var sessionExpiryTime = 24 * 60 * 60;
var sessionExpiryAlertTime = sessionExpiryTime - 5; //assuming we want the alert to show 5 seconds before expiry
setTimeout(function({
alert("Session about to expire!");
}, sessionExpiryAlertTime * 1000); //time is in milliseconds so we multiply by 1000
This works okay as long as the user has JavaScript enabled. If the user reloads the page, the expiry timer updates as per your php code and the setTimeout() function restarts.
This question already has answers here:
PHP Session timeout
(8 answers)
How do I expire a PHP session after 30 minutes?
(17 answers)
Closed 9 years ago.
I want to auto logout from index.php after session expired in 10 minutes. Please help?
I already have this:
//this is login.php
//register the session for user and password
session_register("userName");
session_register("password");
if($userType=="Web_User"){
header("location:index.php?");
}
//index.php
//check session start or not
<?php
if (!isset($_SESSION['start_time']))
{
$str_time = time();
$_SESSION['start_time'] = $str_time;
}
echo $_SESSION['start_time'];
//here I want to expired if user inactive for 10 minutes and redirect to the login.php
?>
I found this in stackoverflow
<script>
var timer = 0;
function set_interval() {
timer = setInterval("auto_logout()", 600000);
// set to 10 minutes
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 600000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "logout.php";
}
</script>
and in the body tag
onLoad="set_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onkeypress="reset_interval();" onscroll="reset_interval();"
You could set a php session timeout or hard code it in like this.
Add this to when a user is logged in.
$_SESSION['start_time'] = strtotime("now");
Add this where you want to check if they have elapsed 10 minutes.
if($_SESSION['start_time'] <= strtotime("-10 minutes"))
{
//Log them out.
}
If user is inactive for some specific duration, then it should autometically log out. So how I can do this using codeigniter?
OR
how to check whether user is active or not after login on that site?
// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
You can save the time that your user logged-in in a session or a cookie
Example: $this->session->set_userdata('time', time());
and use a javascriptjQuery function (Exp. $.getJSON('time.php', function (data) {alert(data.serverTime);});) or anything else to check the current time. Then, log your user out when needed.
However, next time, please place code or something else that shows your efforts.
<?php
$minutes=3;//Set logout time in minutes
if (!isset($_SESSION['time'])) {
$_SESSION['time'] = time();
} else if (time() – $_SESSION['time'] > $minutes*60) {
session_destroy();
header(‘location:login.php’);//redirect user to a login page or any page to which we want to redirect.
}
?>
... which was originally taken from skillrow.com/log-out-user-if-user-is-inactive-for-certain-time-php/ (now 404).