質問があります。この小さなスクリプトを作成して、特定の IP が Web サイトにフラッディングしているかどうかを確認しました。その場合、.htaccess ファイルで IP を拒否します。私の質問は、このスクリプトがまったく役に立たないか、試してみる価値があるかどうか誰か教えてもらえますか...スクリプトは構成ファイルで呼び出されるため、すべてのページロードで実行されます。
<?php
#get the visitor ip
$ip = $_SERVER["REMOTE_ADDR"];
#start the session
@session_start();
#check if the ip is banned
if( $_SESSION['~b'] ){
#check if we can open htaccess
$fp = @fopen('./.htaccess','a');
if($fp){
#add the ip to htaccess
@fwrite($fp,"\r\ndeny from $ip");
#close
@fclose($fp);
#destroy the session
@session_destroy();
@mail("my-email","IP Banned","Ip: $ip");
}
#let the user know why we deny him or her access
die('To many requests.');
}
#get the filename and location
$f = './log/'.@ip2long($ip);
#check if the file exists
if ( @is_file($f) ) {
#get the last filetime
$a = @filemtime($f);
#touch the file, give a new filetime
@touch($f,time());
#the ip is not banned
$_SESSION['~b'] = false;
#add the time diff
$_SESSION['~r'] += @time()-$a;
#add the latest hit
$_SESSION['~h'] += 1;
}else{
#create the file if it doesn't exist
@file_put_contents($f,''); #size: 0kb
#if touch() doesn't work
#chmod($ipfile,0755);
}
#calculate the diff after 10 hits, and ban when the avg is smaller than 0.25 seconds
if( $_SESSION['~h'] > 10 && ($_SESSION['~r']/$_SESSION['~h']) < 0.25 ) $_SESSION['~b'] = true;
?>
セッションを回避するためのアドバイスに従っただけなので、Cookie とセッションに依存することなく、ファイル ベースにしました。
<?php
# get the visitor ip
$i = $_SERVER["REMOTE_ADDR"];
# get the filename and location
$f = './log/'.ip2long($i).'.dat';
# check if the file exists and we can write
if ( is_file($f) ) {
# get the last filetime
$a = filemtime($f);
# get the file content
$b = file_get_contents($f);
# create array from hits & seconds
$d = explode(':',$b);
# calculate the new result
$h = (int)$d[0] + 1;
$s = (int)$d[1] + (time()-$a);
# add the new data tot text file
file_put_contents($f,"$h:$s",LOCK_EX);
unset($d);
}else{
# create the file if it doesn't exist hits:seconds
file_put_contents($f,"1:1",LOCK_EX); #size: 3kb
# to make sure we can write
# chmod($f,0755);
# set the hits to zero
$h = 0;
}
# create a result var
$r = $h > 10 ? (float)$s/$h : (float)1;
# calculate the diff after 10 hits, and ban when the avg is smaller than 0.20 seconds (5 hits per second)
if( $r < 0.20 ) {
# check if we can open htaccess
$fp = @fopen('./.htaccess','a');
if($fp){
# add the ip to htaccess
@fwrite($fp,"\r\ndeny from $i");
# close
@fclose($fp);
# mail the admin
@mail("email","IP Banned","Ip: $i with $r sbh (Seconds Between Hits)");
}
# let the user know why we deny him or her access
die('To many requests.');
# remove the file
unlink($f);
}
# if the user leaves, reset
if( $r > 30 ) {
unlink($f);
}
echo 'Result: '.$r.'sbh (Seconds Between Hits)';
?>