我需要一個方法獲取兩個字符串,表示DateTime
(在MySql
語法中)並返回它們之間的時間差。
然後我需要將該時間與3 seconds
進行比較,以便在我的服務器上阻止暴力攻擊。在PHP中比較時間字符串
我已經搞砸了很多谷歌,我設法得到DateTime對象的字符串表示,但我無法設法轉換和比較它們。
我需要一個方法獲取兩個字符串,表示DateTime
(在MySql
語法中)並返回它們之間的時間差。
然後我需要將該時間與3 seconds
進行比較,以便在我的服務器上阻止暴力攻擊。在PHP中比較時間字符串
我已經搞砸了很多谷歌,我設法得到DateTime對象的字符串表示,但我無法設法轉換和比較它們。
$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
}
strtotime($timeStr)
它將轉換爲自時代以來的秒數。然後你可以使用標準的數學運算符。被警告,時間可能有時不準確。要轉換回來,date("m-d-Y H:i:s", $time)
上的MySQL方面:
SELECT UNIX_TIMESTAMP(my_time) FROM my_table
在PHP端,你就必須在幾秒鐘內,你可以比較UNIX時間戳。
$diffInSeconds = $dateTimeLater->format('U') - $dateTimeFirst->format('U');
繼承人使用會話,無需查詢數據庫的時間戳的替代方法:
<?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';
}
?>
你能後至今你已經嘗試了什麼? –
什麼是BF攻擊? –
蠻力攻擊,我想。 –