You should read documentation rewind.
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
choose another mode from fopen.
Question
I´m testing file creation in PHP. I´m using a comment.php file that has an HTML form and points to list.php file that does all the job, actually.
This is what I have at list.php:
define(ARCHIVO, 'comentarios.txt');
if (!empty($_POST['nombre']) && !empty($_POST['comentario'])){
$nombre=$_POST['nombre'];
$comentario=$_POST['comentario'];
$fp=fopen(ARCHIVO, 'a');
rewind($fp);
fwrite($fp, '<strong>Nombre: </strong>'.$nombre."<br>\r\n".
'<strong>Comentario: </strong>'.$comentario."<br>\r\n".
'<strong>Fecha: </strong>'.
date("d-m-Y")."<br>\r\n<hr>"
);
fclose($fp);
}
$fp=fopen(ARCHIVO, 'r');
fpassthru($fp);
fclose($fp);
Now, my code added all comments one after the other, and I wanted to be the opposite: The newest ones at the top. So I´ve added to this code the rewind($fp);
line, hoping that it would get the file pointer back at the begining of the txt file before adding more stuff.
It doesn´t work, I mean, it still paste the new stuff at the bottom instead of at the top.
What am I doing wrong?
OTHER TIPS
fopen(ARCHIVO, 'a');
Because you are trying to open file with 'a', if you want to write something beginning of file you should user 'w', 'w+', 'r+', 'x', 'x+'
In this case you could try 'r+' but you wont add, will replace beginning of file
if you don't have memory problem you can use 'w'
Like:
fwrite($fp, "Things you like to add beggining of file ++ ".file_get_contents(ARCHIVO));