0

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?

Rosamunda
  • 14,620
  • 10
  • 40
  • 70
  • Note that rewinding won't make your `fwrite()` *insert* data at the beginning of the file — it'll just *overwrite* whatever's there. To insert, you'd need to read the file's entire contents into memory, then overwrite the whole file with the new comment followed by the old ones. And if two users post comments at the same time, you'll probably end up with a corrupted file. That's why SQL databases are typically used for this sort of thing. – Wyzard Nov 21 '13 at 04:16

2 Answers2

4

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.

sectus
  • 15,605
  • 5
  • 55
  • 97
  • Yes, you´re right. Thanks! I´ve tried with fseek($fp, 0); with no luck. I´m using the 'a' mode of fopen, because I want to append new stuff, but keeping the old information. – Rosamunda Nov 21 '13 at 04:17
  • 1
    you cannot insert stuff, only append (add to the end) – sectus Nov 21 '13 at 04:19
0
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));
akakargul
  • 61
  • 7