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?
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: