0

I have some questions about fopen

The first question it’s when i go for add new entry always put to the end of file and no start the file, for example:

$fp=fopen("text.dat","a");
fputs($fp,"Hello 1"."\n");
fclose($fp);

Always the results in this file show to the end:

Hello 1
Hello 2
Hello 3

And no as I want, insert the new comment to the first place for show this as:

Hello 3 
Hello 2
Hello 1 ( The most old entry )

By other side my second question, for example if i have 10 users and this 10 users to the same time insert one entry or post inside this text file, it’s possible or can give me some error? Or I need use flock until save each post, which it’s the best method for no give me problems when some users want change something in the file in the same time?

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103

3 Answers3

1

There's no way to prepend the file automatically. So, it is better to store the existing contents in a temp file and then insert it in the file.

$fp=fopen("text.dat","w");
fwrite($fp,"Hello 1"."\n".fread($fp));
fclose($fp);

This will be outputting as:

Hello 3 
Hello 2
Hello 1

But as far as lock is considered, I don't think it is possible, or am not the right person to answer for this.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0
  1. When you write to a file it'll always append at the end. There's no workaround it which I'm aware of, but in order to achieve what you want (which is to display the lines in reverse order) you can read the lines into an array and display the array in reverse order.
  2. As for locking, only one process can hold the lock to a file, so you don't really have to do anything cause if two users try to update the same file at the same time - only one of them will succeed - which actually creates a different problem (one of the users will lose her post). In order to work around it you should send to the backend both the original copy of the post and the new version submitted by the user, before you save the user's edit - check that the original version is updated. If it's not up-to-date it means that another user changed it meanwhile. The "user-friendly" behavior would be to return an error to the user saying that he's version is not up-to-date but also include his edits - so that he won't have to re-write everything from scratch.
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

For that you need a database, which is more suited for multi-user things and sorting,

Or else use a subdirectory and create every message in its own file, with a file name made up of a sortable timestamp: yyyymmddhhmmss. But then you need to prevent directory caching.

As everyone has the right to be stubborn/cut of an edge: see file_get_contents to load all the contents, and file_put_contents.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138