Locking Files for Multiple Accesses

Web programs are often called by many users at the same time. If more than one person tries to write to a file simultaneously, it can become corrupted. And if one person writes to it while another is reading from it, the file is all right but the person reading it can get odd results. To handle simultaneous users, it’s necessary to use the file locking flock function. This function queues up all other requests to access a file until your
program releases the lock. So, whenever your programs use write access on files that may be accessed concurrently by multiple users, you should also add file locking to them.

$fh = fopen("testfile.txt", 'r+') or die("Failed to open file");
$text = fgets($fh);
fseek($fh, 0, SEEK_END);
if (flock($fh, LOCK_EX))
	fwrite($fh, "$text") or die("Could not write to file");
	flock($fh, LOCK_UN);
echo "File 'testfile.txt' successfully updated";

You may also like...