Filesystem corruption with PHP

Author: seven October 20, 2006

Writing to a file is easy with PHP. But what will happen if 2 processes try to write to a file at once? Exactly, your data might easily become corrupted and useless. You don't want that to happen, of course. That's why you need to implement file locking. flock() is your friend. For writing to a file, you want to obtain an exclusive lock on the file. There must never be concurrent writes to a file, after all. Here's an example.

For reading from a file, you want to obtain a shared lock. Here's an example on how to do this.

Keep in mind that flock() will not work on NFS mounted filesystems or FAT filesystems.

Author
seven
CEO/CTO at Nivas®
Neven Jacmenović has been passionately involved with computers since late 80s, the age of Atari and Commodore Amiga. As one of internet industry pioneers in Croatia, since 90s, he has been involved in making of many award winning, innovative and successful online project. He is experienced full stack web developer, analyst and system engineer. In his spare time, Neven is transforming retro-futuristic passion into various golang, Adobe Flash and JavaScript/WebGL projects.

    Leave a Reply

    Your email address will not be published. Required fields are marked *