PHP Session timeout - php

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
}
?>

Related

Cookie warning alert doesnt dissapear on first click

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.
I use this following function to check if cookie exists or not.
function checkIfCookieExist($cookieName) {
if(isset($_COOKIE[$cookieName])) {
return true;
}
else {
return false;
}
}
if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
}
Prints out the cookie bar, links to index with a get parameter for the cookie
function renderCookieBar() {
echo('
<div id="cookieBar">
<p>blabla cookie, cookies on this site yo</p>
I understand, close this box!
</div>
');
}
Calls function to print out cookiebar at given place in my html code
if(!checkIfCookieExist('cookieConfirmation')) {
renderCookieBar();
}
I appreciate any answers or help,
Cheers!
When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.
Check the manual: http://php.net/set_cookie
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
You can either
1. Set the cookie and immediately reload the page
Set the cookie and force a browser refresah by using header("Refresh:0");.
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
header("Refresh:0");
}
2. Use Javascript
When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.
There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

I need to block login after 3 attempts [duplicate]

This question already has answers here:
How can I throttle user login attempts in PHP
(11 answers)
Closed 9 months ago.
So I have this code:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
}
if(isset($_SESSION['count'])) {
$_SESSION['count']++;
$num = 3 - $_SESSION['count'];
echo $num.' login attempts left.';
if($_SESSION['count'] < 0)
{
session_destroy("count");
unset($_SESSION["count"]);
echo 'negative :/';
}
}
if($_SESSION['count'] == 3)
{
echo 'Your session is locked for 30 minutes.';
if(!$_SESSION['timeout'])
{
$_SESSION['timeout'] = time();
}
$st = $_SESSION['timeout'] + 180; //session time is 30 minutes
if(time() < $st)
{ }
elseif(time() >= $st) {
session_destroy("count");
session_destroy("timeout");
unset($_SESSION['count']);
unset($_SESSION['timeout']);
}
}
?>
Somewhere the is an error but I can't find it :(
I just need to limit the login attempts without using a database, just simple sessions.
Can you help me?
First of, your second if should be an else I think.
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
...
Otherwise the first statement will check if $_SESSION['count'] is unset.
If so it will set it to 0. Then for the second if it will be set and $_SESSION['count']++; will then alway increase this count to 1. So it will at least always be 1.
The second thing is that you don't decrease the count anywhere in the code.
So it will never reach 0.
If you explain more on what the exact error is, we could help you better.
Please keep in mind that session base authentication can be annuled using easy methods. E.g. visiting your site through tor or use a proxy every time the login limit has been reached.
You think a hacker is gonna store a session cookie and help you out?
You can't do brute-force protection using sessions. You need application state.
Here's my answer to a previous question: Block request for multiple unsuccessful logins for a period of time
You don't need to write to a file. Foreach time your user tries to login and it returns false. You should add +1 to your _SESSION['count']. Put that code into a function. Your _SESSION['count'] is global so when its 3 your user will be locked out.

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.

Automatic Logout after 15 minutes of inactive in 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

Categories