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?
What happens when multiple users fopen same file?
Moderator: General Moderators
Re: What happens when multiple users fopen same file?
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?
That's half correct. In 'append' mode, writes are atomic - quoting the manual:
http://php.net/manual/en/function.fwrite.phpNote: 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.
Re: What happens when multiple users fopen same file?
@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?
@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?
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?
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.