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.