Handling File Read/write Concurrency Problem in PHP

Recently I need to use file for caching little bit of data. Then I thought of concurrency problem can arise in File based structure due to read/write issue. For small data and that also if  not so useful , usage of Database can be avoided. Though Database can handle any kind of conflict and other kind of problems very easily.

Though I do not need to use file based structure or any caching for my program, I just found interesting to mention it here.

PHP has a flock() function to lock a file. It takes first parameter as file pointer and second parameter take operation you want to perform. and third is wouldblock. wouldblock can be True/False but it is not mentioned in example in PHP documentation and instead of that an Operation (LOCK_NB) is mentioned. PHP would wait until lock is achieved. This can take much time depending on the file availability for locking.

Here is simple example of file locking in PHP:

$file = fopen('/tmp/fileToLock.txt', 'w+');
if (flock ($file, LOCK_EX)) { // exclusive lock
	fwrite($file, "write the data");
	flock ($file, LOCK_UN); // lock released
}
else {
	echo "Could not lock the file.";
}

Here program will wait until it gets the lock or script timeout. To avoid the locking or to give others to use the resource, you can use different method.

Here is code that do not block in case of not getting the file lock:

$file = fopen('/tmp/fileToLock.txt', 'w+');
if (flock($file, LOCK_EX|LOCK_NB))
{
	echo 'File is locked. Perform desired operation.';
}
else
{
	echo 'File is in use by another program. Try again latter.'
}

I will prefer this code, if locking is not very essential.

Here is the script to give others to take resource in case lock in not available right now. This a user contribute note on PHP documentation. See if it work!

$file = fopen('/tmp/fileToLock.txt', 'w+');
while (! flock ($file, LOCK_EX)) {
	usleep(1000);
}

For more details on File lock in PHP, read about file locking function (flock). Here is also a good discussion about concurrency.

Comments are open for an year period. Please, write here on Facebook page.