Expire unix or time() code after x hours - php

I am trying to create a forgot password feature which will expire the link created after x hours. So I am storing time() data in database value when a user requests a password reset. So how can I expire it?

three options:
compare the time you saved on the db with the one you get when the user click the link
Use a cron job and make it run periodically
Just don't save in the db and make the link to care about everything. You could use a signature + a salt to avoid users to modify this link
like:
$now = time();
$sk = sh1($user_id . $now . "yoursupersalthere")
$link = "http://www.example.com/forgot.php?id={$user_id}&ts={$now}&sk={$sk}"
that will be the link you sent to the user. Then to make the check
$ts = $_GET['ts'];
$user = $_GET['id'];
$sk = $_GET['sk'];
if (!$sk == sh1($user_id . $now . "yoursupersalthere")) {
die("bad signature");
}
elseif (time() - $ts > 3600 /* or put your expiration limit */) {
die('link expired');
}
// do your job

You're probably having a table entry with a reset link, just add a date field to it, and then either include a WHERE expiredate<NOW() or clean the table from time to time with a simple DELETE from table WHERE expiredata<NOW().

One method of doing this is to check to see if the link is expired when the link is clicked -- some pseudo-code:
// when the link is clicked pull the information from the database and get the time
// SQL goes here
// this will give you the difference in seconds
$diff = time() - $timestamp_from_db;
// we'll pretend the time expires in 8 hours
$expires_in = 8 * 60 * 60;
// for this example we'll pretend the expiration is 8 hours
if($diff <= $expires_in)
{
// has not been more then 8 hours
}
else
{
// has been more then 8 hours
}

The best way to do this that keeps the table clean is to implement the following:
The table needs at least the account ID with a UNIQUE index and foreign key to the accounts table, the hash with a UNIQUE index and a timestamp.
In the page that creates the link, do not allow "reset my password" based on information that can be obtained by a random person. If you do this, one can fill your table with reset password requests and generate spam and security concerns with your users.
In the page where the link is verified first delete all expired records by comparing NOW() with the stored timestamp, then simply SELECT using WHERE='$hash' (of course, you sanitize $hash). Given the UNIQUE index on the hash, this can only return one row or no rows.
The UNIQUE index on the account ID ensures that people cannot request multiple resets within the expiration time.

Related

How to make token valid as per user using PHP and MySQL

I need one help. I am doing the token based login Webservice using PHP and MySQL. Here I am setting the time duration, If no activities are happened within that time interval the code should return the failed status. I am explaining my table below.
db_user:
id user_id token added_time
1 2 aqs234reftgyh 31-01-2018 12:23 PM
The above is my table with the required token and date-time for user_id=2. Here my need is each time of user action the input will be user_id=2 and token=aqs234reftgyh pass from user end to match with database. If the current user action time is more than 15 min of token added time then the code will return as false otherwise true.
calculate the time difference and if it exceeds 15 minutes then return false
$endTime = strtotime("+15 minutes", strtotime($added_date));
$currentTime = strtotime(date("d-m-Y H:i:s p"));
if(round(abs($currentTime - $endTime) / 60,2) > 15){
return false;
}

Limit the access of a function to once every 24 hours PHP + MySQL

I would like to limit the access of a function i've created to once every 24 hour based on the users IP address. I would also like the PHP script to delete the MySQL record if it's older than 24 hours.
If the user already has used the function within 24 hours, show them a message and prevent the script from continue running.
If the user already has used the function but 24 hours has passed since he used the function, delete the MySQL record and let the script continue running.
I'm lost and as you can see i am also missing some statements for deleting old records (-24 hours)..
Could anyone provide me with an example of how to do this? Thanks
Get client's IP address and store it with current date and time if the record doesn't exist.
Fetch the record and add 24 hours to its date and time value and check it with the current date and time every time the script is executed.
You need if else conditional statements to check if the 24 hours time is over or not. Based on that, you will control the execution of the function you want to.
I think I don't want to write much of theory. Here, I've written the pattern what the code looks like:
if(!$record_in_db) {
// create record with the client's ip address and the current date and time
// invoke the function you want - This is the code to trigger the function first time for the new IP address
} else {
// fetch_record_from_db
// add 24 hours to its date and time value
// check it with current date and time
$record_date_time = new DateTime('22-12-2016 22:45:20'); // this value should be fetched from database
$record_date_time_by_24_hours = $record_date_time->modify('+1 day');
$current_date_time = new DateTime(date('d-m-Y H:i:s', strtotime('now')));
$date_time_diff = $current_date_time->diff($record_date_time_by_24_hours);
if($date_time_diff->invert == 0) {
// Do something
} else {
// update the date and time of the record to NOW which is current date and time
// invoke the function you want
}
}
I can't write you the whole code. I could only give you some hints. You need to build the code from it. Hope I've given you right hints that could help you.

PHP Check if a user is online

Could anyone tell me why this doesn't work? In my database lastactive is 2013-12-10 16:15:12, updates every time a user refreshes any page on my website.
I select it and set it as a variable:
$lastactive = $row[5];
Here's where I thought it should work, but doesn't. Using 10 seconds for testing.
if(time() > $lastactive+10){
print('<div id="user_online_status" style="color: #aaa;">[OFFLINE]</div>');
}
else if(time() < $lastactive+10){
print('<div id="user_online_status">[ONLINE]</div>');
}
You're comparing a unix timestamp to a MySQL datetime string. You need to convert it to a unix timestamp before comparing the two:
$lastactive = strtotime($row[5]);
Replace your SELECT statement from:
SELECT lastOnline FROM user
to something like...
SELECT UNIX_TIMESTAMP(lastOnline) FROM user
that's it. You're currently checking the Date string against a UNIX Timestamp.
I dont see its good idea to check for time.
What if user doesnt refresh the page , he let the page open and went to eat ? . he will be loggedout? it will be anonying.
I guess better is to use unload
$(window).unload(function() {
// Send an Ajax request to logout.php
});
if user doesnt refresh the page, you can check it on server using cron.
$limit = $userOnline+60; // cron set to run every minute
if($userOnline < $limit)
$userStatus = "offline";
else
$userStatus = "online";

php setcookie for link

Here is my code
i have html link like this
<?php echo $pro_name;
these php values coming from database it has (thousands of) number of results, here i need to set cookie for this links.
If its clicked means i need to store that links in cookie and i need to show last five viewed links in another page.
If I understand, you just need to bind the setting of a cookie to the clicking of the link?
If so, you need to add an ID to your <a>:
In English
Then bind some cookie-setting code to the click event:
(Using jQuery)
$("a#mylink").bind("click", function() {
$.cookie("TR_LNG", "English");
});
Edited. Set expires time(for example for 30 minutes):
30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "foo", { expires: date });
You don't need cookies for this. If I undertsand your problem, you simply need to keep track of the last N requests to your app from a certain user. You need users to be associated with a session, and at the top of each and every page you want to track you need to:
session_start();
$hits = $_SESSION['last_hits'];
array_push($_SESSION['last_hits'], getExternalUrl());
if (count($hits) > 5) {
array_shift($hits);
}
You'd better implement a framework instead of manually adding this snippet at the top of every PHP file. Also note that I used getExternalUrl() because if the PHP server is reverse proxied, the request path may not contain the actual URL (not sure what you really need, tough). Appending the page token to the query string may be ok, too, but it all depends on your needs.

How to expire the activation link in PHP?

I have a php script that sends an activation link via email to the users so they can activate their account. The link is like this: mysite.com/activation.phpid?id=20
How can I create the link to expire after 24 hours?
I haven't tried anything as I couldn't find anything to teach me how to do it. all I know is that I might be able to do this by storing something in mysql but how?
it will be great if someone could tell me the step by step instruction please.
Thanks
Make the link like this:
$time = time();
$hash = md5($id . $time . "somerandomsalt"); // check this again in activation.php
$link = "activation.php?id=" . $id . "&hash=" . $hash . "&time=" . $time;
Then in activation.php you check if the hash matches. Oh, and check the time of course :P
You could obfuscate it a bit to hide the id, hash and time query parameters, but this is the basics.
Just add an extra field in your database with the expiration date of the link. When the link is clicked you can then check the date to make sure it isn't expired.
edit
I'm guessing at your column and table names.
SELECT IF (DATEDIFF(date_registered, CURRENT_TIMESTAMP) <= 0, 1, 0) AS expired
FROM users
WHERE id = 20
If expired is 1 then the link is expired. If it is 0 then it is valid.

Categories