将PHP中的时间比较为字符串

时间:2011-09-10 16:50:47

标签: php sql datetime compare

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

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

5 个答案:

答案 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 :(得分:1)

strtotime( $timeStr ),它将转换为自纪元http://en.wikipedia.org/wiki/Unix_epoch以来的秒数。然后你可以使用标准的数学运算符。请注意,strtotime有时可能不准确。要转换回date("m-d-Y H:i:s", $time)

答案 2 :(得分:1)

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

答案 3 :(得分: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';
}
?>

答案 4 :(得分:-1)

在MySQL方面:

SELECT UNIX_TIMESTAMP(my_time) FROM my_table

在PHP端,您可以在几秒钟内获得UNIX时间戳,您可以对其进行比较。