I'm not quite sure about your question - do you want to write data and not overwrite the beginning of an existing file or write new data to the beginning of an existing file, preserving the existing content after that?
To insert text without overwriting the beginning of the file , you will have to open it to add ( a+ not r+ )
$file=fopen(date("Ymd").".txt","a+") or exit("Unable to open file!"); if ($_POST["lastname"] <> "") { fwrite($file,$_POST["lastname"]."\n"); } fclose($file);
If you are trying to write to the beginning of the file , you will need to read the contents of the file (see file_get_contents ), then enter a new line and then the contents of the file into the output file.
$old_content = file_get_contents($file); fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limitations when trying to read a large file using file_get_conents . In this case, consider using rewind($file) , which sets the file position indicator for the handle to the top of the file stream. Please note that when using rewind() do not open the file with the parameters a (or a+ ), for example:
If you opened the file in append mode ("a" or "a +"), any data that you write to the file will always be added regardless of the position of the file.
source share