Reputation: 5550
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.
Upvotes: 0
Views: 675
Reputation: 46602
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';
}
?>
Upvotes: 1
Reputation: 45589
$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
}
Upvotes: 2
Reputation: 6252
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)
Upvotes: 1
Reputation: 131891
$diffInSeconds = $dateTimeLater->format('U') - $dateTimeFirst->format('U');
Upvotes: 1
Reputation: 8073
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.
Upvotes: -1