ExpertRefresh

Streams / File lock  

1) Lock a file






flock() <?php // Lock a file $fp = fopen("example", "r+"); if (flock($fp, LOCK_EX)) { // exclusive lock ftruncate($fd); fwrite($fd, 'abc'); fflush($fd); // flush output before releasing the lock flock($fp, LOCK_UN); // release the lock } else { echo "Couldn't get the lock!"; } Atention:

Assigning another value to handle argument in subsequent code will release the lock.

On some operating systems flock() is implemented at the process level.

You must remember that flock() uses a "cooperative" locking mechanism with one big assumption: that all other processes that want to access your file will also use flock(). Therefore, you can create a temporary directory and "hold it" until you have finished your I/O operations.


References