Compare times in PHP as string - php

I need a method that gets two strings that represents a DateTime (in the MySql syntax) and returns the time difference between them.
Then I need to compare that time to 3 seconds so I could block a Brute Force attack on my server.
I've messed a lot with Google and I managed to get the string representation of the DateTime object, but I can't manage to convert and compare them.

$time_str1 = '2011-09-10 19:59:23'; // first string datetime from DB
$time_str2 = '2011-09-10 19:59:24'; // second string datetime from DB
// first DateTime object created based on the MySQL datetime format
$dt1 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str1);
// second DateTime object created based on the MySQL datetime format
$dt2 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str2);
// difference comparison to check if at least 3 seconds have passed
if ( ($dt2->format('U') - $dt1->format('U')) > 3) {
echo 'Ok, no brute force'; // yes, three seconds have passed
} else{
echo 'We got you newbie'; // nope, three second haven't passed
}

$diffInSeconds = $dateTimeLater->format('U') - $dateTimeFirst->format('U');

strtotime( $timeStr ) which will convert to the amount of seconds since epoch http://en.wikipedia.org/wiki/Unix_epoch . Then you can just use standard mathematical operators. Be warned, strtotime can be inaccurate sometimes. To convert back, date("m-d-Y H:i:s", $time)

Heres an alternative method using a session, no need to query a db for a timestamp:
<?php
session_start();
function post_check($limit){
//Check for first time
if(isset($_SESSION['post_check'])){
//Check for count on failed
if(isset($_SESSION['post_check_count'])){
//If fail count is more then 3 block till user closes down browser
if($_SESSION['post_check_count']>$limit){
die('Too many requsets to the server, please close down your browesr and try again.');
}
}else{
//Set for count on failed
$_SESSION['post_check_count']=0;
}
//Check (time-limit) against timestamp held in session
if(($_SESSION['post_check']+$limit)<=time()){
//Update timestamp
$_SESSION['post_check']=time();
//Ok
return true;
}else{
//Update Fail count
$_SESSION['post_check_count']++;
//Fail
return false;
}
}else{
//Set for first time
$_SESSION['post_check']=time();
return true;
}
}
//Pretty self explanitry here
if(post_check('3')===true){
echo 'Allowed: handle post stuff here';
}else{
echo'Too many requests within given time limit do nothing';
}
?>

On the MySQL side:
SELECT UNIX_TIMESTAMP(my_time) FROM my_table
On the PHP side, you then have UNIX timestamps in seconds, which you can compare.

Related

How to make email link expire after X minutes in php?

I am working on email link expire after some X minutes where X denotes some random date_time. so my motive is to expire the the link after some time what ever I set the date_time in side the $expire_date.
So I just created dummy code myself just in order to sure my code works or not.
$currentDateTime = new \DateTime();
$currentDateTime-> setTimezone(new \DateTimeZone('Asia/kolkata'));
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";
if($now > $expire_date)
{
echo " link is expired";
}
else{
echo " link still alive ";
}
I guess I am missing something in the above code, somehow the above code isn't working if anyone would point out the right direction or some better implementation it would be great.
You are comparing the times as strings. This does not work, as your first formatted string has a leading space.
Instead, try either removing the whitespace, or better, compare the times as DateTime objects:
$timezone = new \DateTimeZone('Asia/kolkata');
// Create the current DateTime object
$currentDateTime = new \DateTime();
$currentDateTime-> setTimezone($timezone);
// Create the given DateTime object
$expire_date = "02:59PM 26-Mar-2019";
$expireDateTime = \DateTime::createFromFormat($expire_date, 'h:iA j-M-Y');
// Compare the objects
if($currentDateTime > $expireDateTime)
{
echo " link is expired";
}
else{
echo " link still alive ";
}
If you want to compare dates in PHP, your best bet is to use UNIX time stamps. A UNIX time stamp is the number of seconds since the UNIX epoch (00:00:00 Thursday, 1 January 1970).
time() will return the current UNIX time stamp.
strtotime() will convert a date string into a UNIX time stamp.
So replacing these two lines:
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";
With these:
$now = time();
$expire_date = strtotime("02:59PM 26-Mar-2019");
Should solve your problem.
You are comparing date strings which will not work. You have to parse the string to a datetime object or timestamp before you can compare these values.
For example, using timestamps:
$expire_date = "02:59PM 26-Mar-2019";
if (time() > strtotime($expire_date)) {
echo "link is expired";
} else {
echo "link still alive ";
}
All you have to do is use strtotime function and add inside date function and here you can specify day, hour, minutes, seconds as a perimeter. This way you can set time manually by adding +5 minutes or so on..
date_default_timezone_set("Asia/Kolkata"); // set time_zone according to your location
$created = "2020-08-14 17:52"; // time when link is created
$expire_date = date('Y-m-d H:i',strtotime('+1 minutes',strtotime($created)));
//+1 day = adds 1 day
//+1 hour = adds 1 hour
//+10 minutes = adds 10 minutes
//+10 seconds = adds 10 seconds
//To sub-tract time its the same except a - is used instead of a +
$now = date("Y-m-d H:i:s"); //current time
if ($now>$expire_date) { //if current time is greater then created time
echo " Your link is expired";
}
else //still has a time
{
echo " link is still alive";
}

PHP - Comparing Database DateTime with Current DateTime

I've seen a few different DateTime comparisons on StackOverflow, but I can't seem to get it right. I need to be able to retrieve a row from the database, compare the DateTime with the current DateTime, and then evaluate whether or not it.
In this case, I need to check if the current row has expired or not.
if (strtotime(new DateTime()) > strtotime($row['expiration_date'])) {
$response = 'Valid Coupon!';
} else {
$response = 'Coupon Expired';
}
I've tried a few different ways, but none seem to work properly.
"2017-07-15 13:42:31 > 2017-07-15 14:27:31"
// and
"2017-07-15 13:42:31 > 2017-07-14 13:03:04"
Both return as a Valid Coupon.
I've tried a number of things, but can't seem to figure out why these dates aren't working properly. Any thoughts?
Use ->format
if (strtotime((new DateTime())->format("Y-m-d H:i:s")) > strtotime($row['expiration_date'])) {
$response = 'Valid Coupon!';
} else {
$response = 'Coupon Expired';
}
Check this live : https://eval.in/833030
Or you can use
(new DateTime())->getTimestamp();
Instead of
strtotime((new DateTime())->format("Y-m-d H:i:s"));
Check this : https://eval.in/833038
You should change your new DateTime() and expatriation date and time into Unix timestamp.
When you convert your date into Unix timestamp, it will show in a number format. This way, you will compare your value.
For example:
$current_date = strtotime(new DateTime); //your current date and time
$expatriation_date = strtotime($row['expiration_date']); //your database data and time values //
if($current_date > expatriation_date ){
$response = 'Valid Coupon!';
}
else{
$response = 'Coupon Expired';
}
Your current date and time in Unix timestamp is "1500118951" and expatriation date and time in Unix timestamp is "1500121651". You can compare your value easily.

Get the date from a time string

Is there a way to convert an input time string (ex: 01:13) to a Zend date object, so that I store it later in a timestamp column in a Mysql database.
Examples:
If the current datetime is 2013-07-15 17:33:07 and the user inputs 18:05 the output should be 2013-07-15 18:05:00.
If the current datetime is 2013-07-15 17:33:07 and the user inputs 02:09 the output should be 2013-07-16 02:09:00. Notice that since the time entered was lower than the current time, so it was treated as tomorrows time.
I simply want to get the next point in time that satisfies the entered time. I'm open for solution using plain PHP or Zend_Date.
I think you should compare the current time with the time entered by the user and create a DateTime object of either "today" or "tomorrow". DateTime accepts strtotime() relative time parameters.
Quick hack. Works as of today, 15.07.2013 23:58 local time:
$nextTime = new DateTime('today 18:10');
if ($nextTime < new DateTime('now')) { // DateTime comparison works since 5.2.2
$nextTime = new DateTime('tomorrow 18:10');
}
echo $nextTime->format('d.m.Y H:i:s');
here is working example for you just add your dynamic variable to check date with user inputs
You can use mktime function to manage your date.
$input_date = date("Y-m-d H:i:s",mktime(18,05,0,date("m"),date("d"),date("Y")));
echo "current time".$current_time = date('Y-m-d H:m:s');
echo "<br>User input is ".$input_date;
if(strtotime($current_time) > strtotime($input_date)){
$input_date = date("Y-m-d H:i:s",mktime(18,05,0,date("m"),date("d")+1,date("Y")));
echo "in";
}else{
// nothing to do
}
echo "<br> result->".$input_date;
i hope it will sure solve your issue

Comparing a date to current server date using PHP

I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);

Looping through dates until a free one is found

I have a function which checks my database to see if a date exists, if it does exist, i want to display the next date which isnt in the database.
Is this possible?
My function returns 1 if there is a date in the database and 0 if there isnt, im using codeigniter, but not using any built in functions.
Its basically an availability checker, it allows us to input many different dates in the database, so calling my function i use
$availcheck = $ci->availability->check_availability_by_date(date('d/m/Y'));
The i use a if statement to check if the first time it runs it returns a value, this is how i have it
if($availcheck > 0){
// loop through the next dates and run the function again to see if it returns 0
} else {
echo 'available now';
}
I guess i would add 1 to the current date, check that one, then add another 1 and check that and so on.
Im just not sure how.
Cheers,
if i understand you correct , your problem is adding the day ?
if so i would suggest using the epoch or unix time
so convert the date to unix time using mktime than just add 1 day in seconds (24*60*60)
and then convert back to d/m/y format.
you can use the date function.
$date = time(); // get current timestamp
while ($availcheck) // while date IS found in database
{
$availcheck = $ci->availability->check_availability_by_date(date('d/m/Y',$date));
$date = $date + (24*60*60); // add one day
}
$date = $date - (24*60*60); // reduce one day
echo date('d/m/Y',$date); // prints the first date that is not in the DB
This SQL code could work for me.
$today = date("Y-m-d"); //today
$sql = "SELECT date FROM calendar WHERE date>'{$today}' AND date<='2100-12-31' AND date='0000-00-00' LIMIT 1";
Since you can't determine the ending date, 2100 could be for testing.

Categories