What happens when multiple users fopen same file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Element9
Forum Newbie
Posts: 3
Joined: Sun Apr 18, 2010 6:08 am

What happens when multiple users fopen same file?

Post 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?
solid
Forum Commoner
Posts: 28
Joined: Wed Aug 12, 2009 11:56 am

Re: What happens when multiple users fopen same file?

Post 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.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: What happens when multiple users fopen same file?

Post 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
Element9
Forum Newbie
Posts: 3
Joined: Sun Apr 18, 2010 6:08 am

Re: What happens when multiple users fopen same file?

Post 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?
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: What happens when multiple users fopen same file?

Post 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.
Element9
Forum Newbie
Posts: 3
Joined: Sun Apr 18, 2010 6:08 am

Re: What happens when multiple users fopen same file?

Post 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.
Post Reply