Page 1 of 1

What happens when multiple users fopen same file?

Posted: Sun Apr 18, 2010 6:36 am
by Element9
Hi everyone! This is my first post here.

I am writing a simple guestbook script that uses text file instead of database, so I'm wandering what happens when multiple users fopen the same file (for writing)? Will the script end with an error if it tries to fopen already fopened file or will it wait?

Re: What happens when multiple users fopen same file?

Posted: Sun Apr 18, 2010 7:44 am
by solid
Yes you can get file corruption (loss of data) if multiple users try to write to the same file at the same time. You should really consider using a database here, but at the very least, look into the flock() function.

Re: What happens when multiple users fopen same file?

Posted: Sun Apr 18, 2010 10:38 am
by Eran
That's half correct. In 'append' mode, writes are atomic - quoting the manual:
Note: If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.
http://php.net/manual/en/function.fwrite.php

Re: What happens when multiple users fopen same file?

Posted: Sun Apr 18, 2010 3:33 pm
by Element9
@solid: Thanks. Lots of useful stuff in comments for fopen (in online docs).

@pytrin: Ok, so it won't get corrupted, but will fwrite block or return an error when other process is fwriting?

Re: What happens when multiple users fopen same file?

Posted: Sun Apr 18, 2010 3:51 pm
by Eran
If you are worried about contention, use a database. You can implement a read/lock mechanism using a flat file, but why would you - a database already does that and much better than what you can hope to achieve with reasonable time investment.

Re: What happens when multiple users fopen same file?

Posted: Sun Apr 18, 2010 5:15 pm
by Element9
I switched to database, but I'm still curious about implementing this with a flat file. I'll get deeper into it after I finish the script with db.