简体   繁体   中英

php fopen() and fwrite() under heavy ddos attack

In normal condition , everything is ok, an I can write and create new files with fopen() and fwrite() but under "heavy" DDOS attacks , when file pointer is located at 0 , i cant write anything to file.eg. using "w" mod ,result will be a blank file , but by using "a" or "c" mod , if file not exist or be empty, nothing will be written (and just create a blank file too) , but if file has some characters , it will writes after characters or will clear and rewrite new characters respectively. and when DDOS stopped , everything would be Ok. here is simple code that I'm using for test, what is the problem? Can I fix it?

I'm using php5 in ubuntu with apache and lighttpd...

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fputs($fp, '23');
fclose($fp);
?>

The way I understood the question is that you have problems running this code when there are multiple requests accessing the .php file (and thus the file you are writing to) at the same time.

Now, while it is far from being foolproof, flock() is there to help with this. The basic concept is that you'd ask for a lock of the file before writing and only write to a file if you're able to get the lock to that file, like

$fp = fopen( $filename,"w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX | LOCK_NB)) {
    // do your file writes here

    // when you're done, 
    // flush your file writes to a file before unlocking
    fflush($fp);  
    // unlock the file
    flock($fp, LOCK_UN);
} else {
    // flock() returned false, no lock obtained
    print "Could not lock $filename!\n";
}
fclose($fp);

You can read some more details from the manual entry or this article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM