fwrite writing from beginning without removing

后端 未结 8 1494
误落风尘
误落风尘 2021-01-01 05:08

I am using PHP and fwrite code, but I want every write position to start from the beginning of the file without erasing it\'s content. I am using this code but it is writing

相关标签:
8条回答
  • 2021-01-01 05:46

    This should work:

    $file="name.extension";
    $current = file_get_contents($file);
    $user = $_POST["username"];
    $pass = $_POST["password"];
    file_put_contents($file,$current . "Whatever you want to add here"
    

    This finds the current stuff and copy/pastes it back each time the code is ran (tried to make it as simple as possible in case other answers are a little too complicated)

    0 讨论(0)
  • 2021-01-01 05:48

    So you want to write at the beginning of a file, leaving all of its current contents after the new data? You'll have to grab its existing contents first, then append it back into the file once you've overwritten with your new data.

    $file = 'aaaa.txt';
    $oldContents = file_get_contents($file);
    $fr = fopen($file, 'w');
    fwrite($fr, "text");
    fwrite($fr, $oldContents);
    fclose($fr);
    

    If you want to avoid loading the original file's contents into memory in your PHP script, you might try first writing to a temp file, using a loop buffer or system calls to append the contents of your original file to the temp file, then remove the original file and rename your temp file.

    0 讨论(0)
提交回复
热议问题