Making the variable unset after two minutes - php

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.

Related

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

expiring php redirect on set date

I.m looking for a way in Php to have a Redirect expire on a said day.
The use for this is that I'm sharing file on a sever using the code below.
What I like is to have that redirect take them to a page that lets them know there time is up and they can see the Redirect anymore or tell I update the date of expire.
if (test){
---do something---
die("<script>location.href = 'http://file.here.com'</script>");
} else {
return false;
}
I have also try
function BeforeProcessList(&$conn, &$pageObject)
{
$target_date = new DateTime("05-01-2014");
$today = new DateTime();
if((int)$target_date->diff($today)->format('%r%a') >= 0)
{
header("Location: testview_list.php");
exit();
}
}
There are several scenarios for this case but i suggest to use session.
Use additional session to be taken once your privilege period is valid and make sure that you've already insert a date when a user get into that file along with value that indicate this user is allowed , for example,1 so you can change a value to ,for example,0 after specific period and that user will be denied automatically or redirected to another page
I got it to work.
<?php
// has this expired?
$expire_date = "2015-08-25"; // good until Aug 8/15
$now = date("Y-m-d");
if ($now>$expire_date) {
header("Location: http://yoursite.com/outoftime.html");
die();
}
// and now the unexpired part of the page ...
header("Location: http://yoursite.com/fileshare/");
die();
Thanks for the help guys

need to refresh page to remove sessions

In this code I'm trying to ban client if he/she/it doing to much(10) login request for 3 minutes. The problem is after 3 minutes user must refresh the page 2 times. I can see the reason why it's enter into if statement but I can't find the solution. I feel like I've overcoded.
if($this->sessions->get_data("wrong_login")>10){
if(!isset($_SESSION["ban_time"])){
$this->sessions->set_data("ban_time", time());
}else
{
if(time() - $this->sessions->get_data("ban_time") > 180){ // 180 seconds
$this->sessions->remove("ban_time");
$this->sessions->remove("wrong_login");
}
}
// The message if user still banned
die("Banned for 3 minutes!");
}
I hope I can tell the problem..
EDIT: This code is the inside of the construct of register controller.
Before your IF statement, add another if statement that checks for ban_time session if the time is up, then set the wrong_login session to 0 if it is.
if($this->sessions->get_data("ban_time") < time())
{
$this->sessions->remove("ban_time");
$this->sessions->set_data("wrong_login", 0);
}
remove your else statement there.
also forgot to mention! when you set the ban time, it should be time() + 180.
if(!isset($_SESSION["ban_time"])){
$this->sessions->set_data("ban_time", time()+180);
}
use header function.
e.g.
header("Location: /path/to/some/file.php?error=Banned for 3 minutes.");
Then on the file.php you can do this:
<?php
// Parse error
$error = isset($_GET['error']) ? $_GET['error'] : '';
// Display error (if any) and stop executing the rest of the code.
if (!empty($error)) {
exit($error);
}
?>
This will not work if you already started to output...

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

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