dtkwt62022 2017-03-17 03:03
浏览 43
已采纳

为什么要删除文件的内容?

I've been getting irritated by this bug, and I've tried to fix it but it's been a struggle for me. So I have a php file write to a .txt file, but as I enter different info, it replaces the info that was already in the file, but I don't want it to do that. I want it to add on. Help?

<?php
$filenum = echo rand();
$info = $_GET["info"]; //You have to get the form data
$file = fopen('$filenum.txt', 'w+'); //Open your .txt file
$content = $info. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));

?>

  • 写回答

2条回答 默认 最新

  • dtvgo28624 2017-03-17 03:08
    关注

    You're using w+ mode, and the documentation clearly says:

    Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

    If you want to append, you should use a or a+.

    BTW, I'm not nor sure why you're using w+ rather than just w, since you're never reading the file.

    Also, you can do it all in one statement using file_put_contents()

    $filenum = rand();
    $info = $_GET['info'];
    $content = $info . PHP_EOL . $gain . PHP_EOL . $offset . PHP_EOL;
    file_put_contents("$filenum.txt", $content, FILE_APPEND);
    die(header("Location: " . $_SERVER['HTTP_REFERER']));
    

    And notice that you should have PHP_EOL at the end of $content. Otherwise, every time you add to the file, it will start on the same line as the last line you added previously.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?