File Locking

Contact Us or call 1-877-932-8228
File Locking

File Locking


flock() is used to lock a file so that two or more people do not get access to it at the same time. This helps protect the file from being corrupted. flock() takes two arguments: a file handler and a lock type. flock() does not work with NFS or other networked file systems or with such as FAT that does not support file locking.

Lock Type Explanation
LOCK_SH Reading lock. Others can read file.
LOCK_EX Exclusive lock. The file cannot be opened by others.
LOCK_UN Unlocks file.
LOCK_NB If a file is already locked by another user, flock() waits to get a lock. LOCK_NB tells it not to wait.

The code below shows how we should change Files/Solutions/AddEntry.php to protect Employees.txt from being corrupted.

Code Sample:

---- C O D E   O M I T T E D ----
		flock($myFile, LOCK_EX);
		flock($myFile, LOCK_UN);
---- C O D E   O M I T T E D ----