Automatic Logout after 15 minutes of inactive in php - php

I want to destroy session if users are not doing any kind of activity on website.
At that time after 5 users automatically redirect on index page. How is it possible?
Is possible in php with session handling and for that I have to maintain or update user login time or not..

This is relatively easy to achive with this small snippet here:
if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
echo"<script>alert('15 Minutes over!');</script>";
unset($_SESSION['username'], $_SESSION['password'], $_SESSION['timestamp']);
$_SESSION['logged_in'] = false;
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}

I got this solution from Sitepoint.com
Using a simple meta tag in your html
<meta http-equiv="refresh" content="900;url=logout.php" />
The 900 is the time in seconds that you want the session to be terminated if inactive.
Hope it works for you
Edit: This method does not implement any other logic so will only work if you want to "force" logout as said in the comments

You may create a cookie for a specific time.
For example you could put this on your login page:
<?php
setcookie('admin', 'abc', time()+50);
?>
Then in some file part that is included in every page, like 'header.php', you may include:
<?php
if (!isset($_COOKIE['admin'])) {
echo "<script> location.href='logout.php'; </script>";
}
setcookie('admin', 'abc', time()+50);
?>
In the above example, after 50s the cookie will die and the user will be logged out automatically.

Here is an example of the code.
session_start();
$t=time();
if (isset($_SESSION['logged']) && ($t - $_SESSION['logged'] > 900)) {
session_destroy();
session_unset();
header('location: index.php');
}else {
$_SESSION['logged'] = time();
}

My Solution Is
(i give you solution but this simple and syntax not been tried)
checkerOrCreatorTime.php
<?php
//if using the session, this additional advice me
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
session_start();
//create session (JUST FOR ONE TIME)
if (!isset($_SESSION['THE SESSION KEY FOR LOGIN (EX. USERNAME)'])){
//create anyting session you need
$_SESSION['user']['THE SESSION KEY FOR LOGIN (EX. USERNAME)'] = 'USER';
$_SESSION['user']['TIME'] = '900';
}else
if (time() -$_SESSION['TIME'] > 900){
unset($_SESSION['user']);
// and whatever your decision
}
?>
Faq:
1. Why use ['user'] is session login?
if you using many session for user, you just unset one var, like this.
2. why use a ini_set.... in this syntax?
for more security
if you like using modern web, just using javascript for ajax

<form action="index.php" method="post" name="frm"><input name="uname" type="text" placeholder="User Name" />
<input name="pass" type="password" placeholder="Password" />
<input name="submit" type="submit" value="submit" /></form>
In index.php
<?php if(isset($_SESSION['loggedAt'])) { header('dashboard.php'); }
if(isset($_POST['submit'])) { $name=$_POST['uname']; $pass=$_POST['pass'];
if($name=="admin" &amp;amp;&amp;amp; $pass=="1234") {
session_Start(); $_SESSION['username']=$name; $_SESSION['loggedAt']=time(); header('location:dashboard.php?msg=Welcome to dashboard'); } } ?>
in dashboard.php
if(time() - $_SESSION['loggedAt'] > 240) {
echo"<script>alert('Your are logged out');</script>";
unset($_SESSION['username'], $_SESSION['loggedAt']);
header("Location: " . index.php);
exit;
} else {
$_SESSION['loggedAt'] = time();
}

This code was included in the connection.php to ensure that the code is included in any page but you can implement on any page you want
if (isset($_SESSION['user-session']) OR isset($_SESSION['admin-session']) ) {
//then we are checking the activity sesssion $_SESSION['']
if (isset($_SESSION['last_active'])) {
//if the time is set then we check the difference
$max_time=5*60; #number of seconds
$now=microtime(date("H:i:s"));
//Checking the last active and now difference in seconds
$diff=round(microtime(date("H:i:s"))- $_SESSION['last_active']); #the difference of time
if ($diff>=$max_time) { #if the difference is greater than the allowed time!
//echo "logging out couse the time is".$diff;
header("location:logout.php");
}else {
$time=microtime(date("H:i:s"));
$_SESSION['last_active']=$time; #Updating the time
//echo 'More time added the time was!'.$diff;
}
}else{
//if there is no last active then we create it over here
$time=microtime(date("H:i:s"));
$_SESSION['last_active']=$time;
}}

Simple solution using .htaccess
Add the below lines to your .htaccess file where 3600 is the number of seconds.
Sessions will automatically be destroyed after certain time has nothing to do with the activity or inactivity.
According to the below code session will be destroyed after 1 hour.
php_value session.gc_maxlifetime 3600
php_value session.gc_probability 1
php_value session.gc_divisor 1

Related

php session not being deleted after setting its lifetime

I am a php newbie and practicing with php sessions. Basically, I have a login form which will be shown to a user ONLY if the session does not exist otherwise the page says "User Already Logged In".
I have set the session life time and cookie time using :
session_set_cookie_params(60);
ini_set('session.gc_maxlifetime', 60);
I want the session to be destroyed after 1 minute so that the user will have to log in again. but in my implementation, the session still exists for a long time and the users are logged in.
in my login.php i have:
1: if visited login.php with POST req, then check login credentials
2:if SESSION['logged_in'] is set then do not show the form, echo "already logged in"
<?php
require_once("helpers.php");
session_start();
if(!empty($_POST)){
loginUser($_POST['user_id'], $_POST['pass']);
}
<?php
if(!isset($_SESSION['logged_in'])){
echo "<br>SESSION IS NOT SET UP";
?>
<HTML>
<HEAD>
<LINK rel="stylesheet" type="text/css" href="style.css">
<SCRIPT src="test.js"></SCRIPT>
</HEAD>
<BODY>
<H1>Please login</H1>
<FORM action="login.php" method="post">
<span class=formlabel>Username:</span>
<INPUT name="user_id" type="text" class="forminput" require><BR>
<span class=formlabel>Password:</span>
<INPUT name="pass" type="password" class="forminput" require><BR>
<INPUT type="submit" value="Login" style="width:80px;margin-left:100px;margin-top:3px;"><BR><BR>
Don't have an account? Click here to register.
</FORM>
</BODY>
</HTML>
<?php
}else{
echo '<strong>user already logged in.<br></strong>';
}
?>
Then in my helper.php I have a function:
1: check user id and password in data base
2: if it exists then set a session.
function loginCheck($user_id, $pass){
//here goes code which checks if user_id & pass exists
//store in $RESULT if exists
if(!empty($result)){
session_set_cookie_params(30, '/');
ini_set('session.gc_maxlifetime', 30);
$_SESSION['username'] = $user_id;
$_SESSION['logged_in'] = true;
}
}
Now when ever i log in as a user then the session starts and the login form dissapears, which is the correct behavior that i want. But the session never ends, i mean even if i refresh the page after 10 minutes the form doesn't show up and says "user already logged in".
also:
1: do the sessions gets destroyed by itself after their maxLifetime?
2: if not do we have to destroy it ?
thank you
The gc_maxlifetime value is the number of seconds after which data will be seen as garbage and potentially cleaned up. You'll want to make sure this value is set high enough so that your sessions aren't destroyed too early, but you can't rely on sessions being destroyed after this amount of time.
If you want sessions destroyed after a specific period of time, then you should store a timestamp, and then use that timestamp and the presence of the session to see if the session is still alive. Something like this:
$_SESSION['last_access'] = time();
Then later on, to check if it's still active:
if ( isset( $_SESSION['last_access'] ) && $_SESSION['last_access'] - 60 > time() ) {
// The session is still alive
} else {
// The session should be destroyed
session_destroy();
unset( $_SESSION );
}
Then, your future checks for the presence of any $_SESSION value will work the way you expect.

PHP session time left [duplicate]

I am creating a session when a user logs in like so:
$_SESSION['id'] = $id;
How can I specify a timeout on that session of X minutes and then have it perform a function or a page redirect once it has reached X minutes??
EDIT: I forgot to mention that I need the session to timeout due to inactivity.
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
When the session expires the data is no longer present, so something like
if (!isset($_SESSION['id'])) {
header("Location: destination.php");
exit;
}
will redirect whenever the session is no longer active.
You can set how long the session cookie is alive using session.cookie_lifetime
ini_set("session.cookie_lifetime","3600"); //an hour
EDIT: If you are timing sessions out due to security concern (instead of convenience,) use the accepted answer, as the comments below show, this is controlled by the client and thus not secure. I never thought of this as a security measure.
Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.
<?php
if(!isset($_SESSION["timeout"])){
$_SESSION['timeout'] = time();
};
$st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>
<?php
if(time() < $st){
echo 'Session will last 1 minute';
}
?>
<script type="text/javascript">
window.setTimeout("location=('timeout_session.htm');",900000);
</script>
In the header of every page has been working for me during site tests(the site is not yet in production). The HTML page it falls to ends the session and just informs the user of the need to log in again. This seems an easier way than playing with PHP logic.
I'd love some comments on the idea. Any traps I havent seen in it ?
<?php
session_start();
if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}
else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>
Byterbit solution is problematic because:
having the client control expiration of a server side cookie is a security issue.
if expiration timeout set on server side is smaller than the timeout set on client side, the page would not reflect the actual state of the cookie.
even if for the sake of comfort in development stage, this is a problem because it won't reflect the right behaviour (in timing) on release stage.
for cookies, setting expiration via session.cookie_lifetime is the right solution design-wise and security-wise! for expiring the session, you can use session.gc_maxlifetime.
expiring the cookies by calling session_destroy might yield unpredictable results because they might have already been expired.
making the change in php.ini is also a valid solution but it makes the expiration global for the entire domain which might not be what you really want - some pages might choose to keep some cookies more than others.
session_cache_expire( 20 );
session_start(); // NEVER FORGET TO START THE SESSION!!!
$inactive = 1200; //20 minutes *60
if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
header("Location: user_logout.php");
}
}
$_SESSION['start'] = time();
if($_SESSION['valid_user'] != true){
header('Location: ../....php');
}else{
source: http://www.daniweb.com/web-development/php/threads/124500
<?php
session_start();
if($_SESSION['login'] != 'ok')
header('location: /dashboard.php?login=0');
if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
// session inactive more than 10 min
header('location: /logout.php?timeout=1');
}
$_SESSION['last-activity'] = time(); // update last activity time stamp
if(time() - $_SESSION['created'] > 600) {
// session started more than 10 min ago
session_regenerate_id(true); // change session id and invalidate old session
$_SESSION['created'] = time(); // update creation time
}
?>

Making the variable unset after two minutes

Hey guys am writing a small validation script which uses a simple token to login from the input..When the token is right the user must succesfully login and after two minutes the token must expire and give user a message token expired..But here when i use the token it also came with the message token destroyed ..i want to use the token for 2 minutes and i want the token to be expired in 2 minutes.
I have the html file
<form action="gethints.php" method="post">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
Php file
<?php
$name = $_POST['fname'];
$currenttime = time();
$token = 'sample';
$timetounset = strtotime("2 minutes");
if($name != $token) {
echo 'you cant login';
} else {
echo 'you have succesfully logged in <br>';
}
if($currenttime > time() - $timetounset) {
unset($token);
echo "you cant use this token anymore";
} else {
echo 'token is not destroyed';
}
When i run this code and type sample in the input box i get the message like
you have succesfully logged in
you cant use this token anymore
What i need is when i type the id as sample i want to get the message you have succesfully logged in and after two minute when i use the same id i need to get the message like you cant use this token anymore
Thanks for your help..
Could use a session here:
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request
<?php
if ($_SESSION['timeout'] + 2 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
EDIT:
Don't forget to have session_start(); on top of your code && check if $_SESSION['timeout'] exists, above code is just an example.
The most simple way to approach this imo is to set a cookie with an expiration of 2 minutes.
Store a variable or flag in the cookie and check the contents each time you want to do a validation.
setcookie("TestCookie", $value, time()+120);
Read out the value:
if (isset($_COOKIE['TestCookie'])) {
// Good cookie
} else {
// expired or invalid
}
For information on how to set a cookie and expiration:
http://php.net/manual/en/function.setcookie.php
People can play around with cookies. I suggest you create a database table tokens with token and expires columns. When you insert the token add this to your sql. ...... Insert ....... Timestampadd(now(), interval minute 2); To validate just check if now() is less than expires.

PHP cookies setting

I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.

PHP Session timeout

I am creating a session when a user logs in like so:
$_SESSION['id'] = $id;
How can I specify a timeout on that session of X minutes and then have it perform a function or a page redirect once it has reached X minutes??
EDIT: I forgot to mention that I need the session to timeout due to inactivity.
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
When the session expires the data is no longer present, so something like
if (!isset($_SESSION['id'])) {
header("Location: destination.php");
exit;
}
will redirect whenever the session is no longer active.
You can set how long the session cookie is alive using session.cookie_lifetime
ini_set("session.cookie_lifetime","3600"); //an hour
EDIT: If you are timing sessions out due to security concern (instead of convenience,) use the accepted answer, as the comments below show, this is controlled by the client and thus not secure. I never thought of this as a security measure.
Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.
<?php
if(!isset($_SESSION["timeout"])){
$_SESSION['timeout'] = time();
};
$st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>
<?php
if(time() < $st){
echo 'Session will last 1 minute';
}
?>
<script type="text/javascript">
window.setTimeout("location=('timeout_session.htm');",900000);
</script>
In the header of every page has been working for me during site tests(the site is not yet in production). The HTML page it falls to ends the session and just informs the user of the need to log in again. This seems an easier way than playing with PHP logic.
I'd love some comments on the idea. Any traps I havent seen in it ?
<?php
session_start();
if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}
else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>
Byterbit solution is problematic because:
having the client control expiration of a server side cookie is a security issue.
if expiration timeout set on server side is smaller than the timeout set on client side, the page would not reflect the actual state of the cookie.
even if for the sake of comfort in development stage, this is a problem because it won't reflect the right behaviour (in timing) on release stage.
for cookies, setting expiration via session.cookie_lifetime is the right solution design-wise and security-wise! for expiring the session, you can use session.gc_maxlifetime.
expiring the cookies by calling session_destroy might yield unpredictable results because they might have already been expired.
making the change in php.ini is also a valid solution but it makes the expiration global for the entire domain which might not be what you really want - some pages might choose to keep some cookies more than others.
session_cache_expire( 20 );
session_start(); // NEVER FORGET TO START THE SESSION!!!
$inactive = 1200; //20 minutes *60
if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
header("Location: user_logout.php");
}
}
$_SESSION['start'] = time();
if($_SESSION['valid_user'] != true){
header('Location: ../....php');
}else{
source: http://www.daniweb.com/web-development/php/threads/124500
<?php
session_start();
if($_SESSION['login'] != 'ok')
header('location: /dashboard.php?login=0');
if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
// session inactive more than 10 min
header('location: /logout.php?timeout=1');
}
$_SESSION['last-activity'] = time(); // update last activity time stamp
if(time() - $_SESSION['created'] > 600) {
// session started more than 10 min ago
session_regenerate_id(true); // change session id and invalidate old session
$_SESSION['created'] = time(); // update creation time
}
?>

Categories