程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> php下網站防IP攻擊代碼,超級實用

php下網站防IP攻擊代碼,超級實用

編輯:PHP綜合
今天我開發了下面的代碼,算是大功初成,一天攔截了15個IP,服務器負載正常。
復制代碼 代碼如下:
<?php
//查詢禁止IP
$ip =$_SERVER['REMOTE_ADDR'];
$fileht=".htaccess2";
if(!file_exists($fileht))file_put_contents($fileht,"");
$filehtarr=@file($fileht);
if(in_array($ip."\r\n",$filehtarr))die("Warning:"."<br>"."Your IP address are forbided by some reason, IF you have any question Pls emill to [email protected]!");

//加入禁止IP
$time=time();
$fileforbid="log/forbidchk.dat";
if(file_exists($fileforbid))
{ if($time-filemtime($fileforbid)>60)unlink($fileforbid);
else{
$fileforbidarr=@file($fileforbid);
if($ip==substr($fileforbidarr[0],0,strlen($ip)))
{
if($time-substr($fileforbidarr[1],0,strlen($time))>600)unlink($fileforbid);
elseif($fileforbidarr[2]>600){file_put_contents($fileht,$ip."\r\n",FILE_APPEND);unlink($fileforbid);}
else{$fileforbidarr[2]++;file_put_contents($fileforbid,$fileforbidarr);}
}
}
}
//防刷新
$str="";
$file="log/ipdate.dat";
if(!file_exists("log")&&!is_dir("log"))mkdir("log",0777);
if(!file_exists($file))file_put_contents($file,"");
$allowTime = 120;//防刷新時間
$allowNum=10;//防刷新次數
$uri=$_SERVER['REQUEST_URI'];
$checkip=md5($ip);
$checkuri=md5($uri);
$yesno=true;
$ipdate=@file($file);
foreach($ipdate as $k=>$v)
{ $iptem=substr($v,0,32);
$uritem=substr($v,32,32);
$timetem=substr($v,64,10);
$numtem=substr($v,74);
if($time-$timetem<$allowTime){
if($iptem!=$checkip)$str.=$v;
else{
$yesno=false;
if($uritem!=$checkuri)$str.=$iptem.$checkuri.$time."1\r\n";
elseif($numtem<$allowNum)$str.=$iptem.$uritem.$timetem.($numtem+1)."\r\n";
else
{
if(!file_exists($fileforbid)){$addforbidarr=array($ip."\r\n",time()."\r\n",1);file_put_contents($fileforbid,$addforbidarr);}
file_put_contents("log/forbided_ip.log",$ip."--".date("Y-m-d H:i:s",time())."--".$uri."\r\n",FILE_APPEND);
$timepass=$timetem+$allowTime-$time;
die("Warning:"."<br>"."Sorry,you are forbided by refreshing frequently too much, Pls wait for ".$timepass." seconds to continue!");
}
}
}
}
if($yesno) $str.=$checkip.$checkuri.$time."1\r\n";
file_put_contents($file,$str);
?>

把程序include進要進行的php文件頭部。
程序首先判斷IP是否在禁止列表,如果在則退出;
否則,如果IP在監控列表,10分鐘內點擊超過600次則加入禁止列表。
如果沒有超過時間和次數則次數加1,同時,監控IP是否對同一頁面頻繁操作。
由於是機器刷頻,所以程序不用session判斷。
還有就是更新的時候,不能用獨占處理文件。
使用偽靜態存儲IP也會出錯。
這個程序還有變化和改進的余地的,大家也可以參考QQ農場裡的降級原理,基本上農場也是按照這個原理開發的吧。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved