简体   繁体   English

遭受严重ddos攻击的php fopen()和fwrite()

[英]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. 在正常情况下,一切正常,我可以使用fopen()fwrite()编写和创建新文件,但是在“大量” DDOS攻击下,当文件指针位于0时,我无法向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. 使用“ w” mod,结果将是一个空白文件,但是使用“ a”或“ c” mod,如果文件不存在或为空,则不会写入任何内容(也将创建一个空白文件),但是如果file有一些字符,它将在字符之后写入,或者分别清除和重写新字符。 and when DDOS stopped , everything would be Ok. 当DDOS停止时,一切都会好的。 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... 我在ubuntu中使用php5与apache和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. 我理解问题的方式是,当有多个请求同时访问.php文件(以及正在写入的文件)时,您在运行此代码时会遇到问题。

Now, while it is far from being foolproof, flock() is there to help with this. 现在,尽管它远非万无一失,但flock()可以帮助您。 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 . 您可以从手册条目本文中阅读更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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