All pastes #626752 Raw Edit

badbotbad

public php v1 · immutable
·published 2007-07-19 21:21 UTC
rendered paste body
<?phpdefine( '_B_DIRECTORY', '/home/redelksoftware/logs/' );define( '_B_LOGFILE', 'badbots' );define( '_B_LOGMAXLINES', '1000' );These Constants can be variables or even constant-values within the code - your choice.Directory permissions: `_B_DIRECTORY` needs to be read-writeable by the apache-group.Both $ipLogFile and $ipFile are created on-the-fly if not already existing.//----------------Start-blocking-badly-behaved-bots---------------------------------------------$oldSetting= ignore_user_abort( TRUE );$bInterval= 5;													// secs; check interval$bMaxVisit= 10;													// Maximum visits allowed within $bInterval$bPenalty= 180;													// Seconds before visitor is allowed back$ipLength= 3;													// integer; 2 = 255 files, 3 = 4,096 files$ipLogFile= _B_DIRECTORY . _B_LOGFILE;$ipFile= _B_DIRECTORY . substr( md5( $remote ), -$ipLength );$logLine= '';$time= time();$fileATime= $time;												// access time:-tracks duration$fileMTime= $time;												// modification time:-tracks visitsif( file_exists( $ipFile )) {	$fileATime= fileatime( $ipFile );	$fileMTime= filemtime( $ipFile );		if( $fileMTime < $time ) { $fileMTime = $fileATime = $time; }	$fileMTime++;	$visits= $fileMTime - $fileATime;	$duration= $time - $fileATime;								// secs		if( $duration < 1 ) $duration = 1;		if(( $visits >= $bMaxVisit ) and (( $visits / $duration ) > ( $bMaxVisit / $bInterval ))) {			$fileATime= $time = $time - $bInterval;			$fileMTime= $time + $bMaxVisit + (( $bMaxVisit * $bPenalty ) / $bInterval );			touch( $ipFile, $fileMTime, $fileATime );			header( 'HTTP/1.0 503 Service Temporarily Unavailable' );			header( 'Connection: close' );			header( 'Content-Type: text/html' );			echo "<html><body><p><b>Server under heavy load</b><br />";			echo "$visits visits from your IP-Address within the last $duration secs. Please wait $bPenalty secs before retrying.</p></body></html>";		$remote = $_SERVER[ 'REMOTE_ADDR' ];		$useragent= ( isset( $_SERVER[ 'HTTP_USER_AGENT' ]))		? $_SERVER[ 'HTTP_USER_AGENT' ]		: '<unknown user agent>';		$logLine= "$remote ". date( 'd/m/Y H:i:s' ) ." $useragent\n";		$log= file( $ipLogFile );			if( $fp = fopen( $ipLogFile, 'a' )) {// tiny danger of 2 threads interfering; live with it			if( count( $log ) >= _B_LOGMAXLINES ) {// otherwise grows like Topsy				fclose( $fp );// flock() disabled in some kernels (eg 2.4)				array_shift( $log );// fopen,fclose put close together as possible				array_push( $log, $logLine );				$logLine= implode( '', $log );				$fp= fopen( $ipLogFile, 'w' );			}		fputs( $fp, $logLine );		fclose( $fp );		}	exit();	}}touch( $ipFile, $fileMTime, $fileATime );ignore_user_abort( $oldSetting ); ?>