I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
You get the same opening the file for appending
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (
a+
rather thanr+
)If you're trying to write to the start of the file, you'll have to read in the file contents (see
file_get_contents
) first, then write your new string followed by file contents to the output file.The above approach will work with small files, but you may run into memory limits trying to read a large file in using
file_get_conents
. In this case, consider usingrewind($file)
, which sets the file position indicator for handle to the beginning of the file stream. Note when usingrewind()
, not to open the file with thea
(ora+
) options, as:A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
Composer lib for it can be found here
If you want to put your text at the beginning of the file, you'd have to read the file contents first like: