2011-09-10 71 views
0

我需要一个方法获取两个字符串,表示DateTime(在MySql语法中)并返回它们之间的时间差。
然后我需要将该时间与3 seconds进行比较,以便在我的服务器上阻止暴力攻击。在PHP中比较时间字符串

我已经搞砸了很多谷歌,我设法得到DateTime对象的字符串表示,但我无法设法转换和比较它们。

+1

你能后至今你已经尝试了什么? –

+0

什么是BF攻击? –

+0

蛮力攻击,我想。 –

回答

2
$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 
} 
1

strtotime($timeStr)它将转换为自时代以来的秒数。然后你可以使用标准的数学运算符。被警告,时间可能有时不准确。要转换回来,date("m-d-Y H:i:s", $time)

-1

上的MySQL方面:

SELECT UNIX_TIMESTAMP(my_time) FROM my_table 

在PHP端,你就必须在几秒钟内,你可以比较UNIX时间戳。

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

继承人使用会话,无需查询数据库的时间戳的替代方法:

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