0

I have this script from PHP, .htaccess, DDoS & speedy request protection (The second one without sessions)

<?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\n#DDoS\r\ndeny from $i"); 
        # close
        @fclose($fp);
        # mail the admin
        @mail("email","IP Banned","Ip: $i with $r sbh (Seconds Between Hits)");
    }
    # remove file and let the user know why we deny him or her access
    unlink($f);
    die('To many requests.');

}
# if the user leaves, reset
if( $r > 30 ) {
    unlink($f);
}
echo 'Result: '.$r.'sbh (Seconds Between Hits)';
?>

and it seems to work fine when I access it directly. However when I include it using:

include_once($_SERVER['DOCUMENT_ROOT'] . "/dir/ddos.php");

The page output is some weird text like this: https://i.stack.imgur.com/EZ3tT.png

In the error file there is this line:

[TIME] PHP Warning: file_put_contents(log/1869573999.dat): failed to open stream: No such file or directory in /home/user/public_html/dir/ddos.php on line 22

Oh, and I forgot to mention that this line

echo 'Result: '.$r.'sbh (Seconds Between Hits)';

Is shown as Result: 1sbh (Seconds Between Hits)

Klajdi Him
  • 13
  • 6
  • Did you copy pasted the code from the notepad? – Rajendran Nadar Aug 06 '17 at 12:40
  • Im not sure what you mean by that, but yes, I copied the code from the thread/question I linked above, created ddos.php, pasted pasted text there, created 'log' directory, made 2 text changes and then included the file – Klajdi Him Aug 06 '17 at 12:43
  • I actually fixed the `failed to open stream` error by changing the `$f` to `$_SERVER['DOCUMENT_ROOT'].'/dir/log/'.ip2long($i).'.dat';` – Klajdi Him Aug 06 '17 at 12:48

0 Answers0