Synchronized access to the PHP 5.x file (without a database)

I am mostly familiar with Java, C and C ++, in which there are ways to control that only one thread is accessing a resource at any given time. Now I am looking for something similar, but in PHP 5.x.

To state my problem with one example:

I have an ASCII file that stores only the number, the value of the page load counter. When you deploy the application, the file will simply contain 0. For each access, the value will increase by one. The goal is to track page loads.

The problem occurs when many users access the page containing the counter at the same time. When thread A reads the current value, let's say it's 11, another thread that we call B reads the value, another 11. Then the first thread A increases the read value and writes 12 to the file and closes it. Then the second thread B increases the read value, which is 11, gets 12 and writes it to a file. The value 12 is stored in the file when it really should be 13.

In another programming language, I would solve this with a mutex. I understand that the modules have mutexes, shared memory, and other functionality. But I would like to see a solution that works on "most servers" there. Independent platform. Installed on the cheapest websites. Is there a good solution to this problem? And if not, how would you take it if using a database is not an option ?

+6
synchronization file php mutex
source share
2 answers

You can try the php flock option ( http://www.php.net/flock )

I would imagine something like this (this assumes that the file /tmp/counter.txt already exists and has a counter in the file):

<?php $fp = fopen("/tmp/counter.txt", "r+"); echo "Attempt to lock\n"; if (flock($fp, LOCK_EX)) { echo "Locked\n"; // Read current value of the counter and increment $cntr = fread($fp, 80); $cntr = intval($cntr) + 1; // Pause to prove that race condition doesn't exist sleep(5); // Write new value to the file ftruncate($fp, 0); fseek($fp, 0, SEEK_SET); fwrite($fp, $cntr); flock($fp, LOCK_UN); // release the lock fclose($fp); } ?> 
+7
source share

The PHP flock () function is the route. However, you must ensure that all file access is protected by calling flock (). PHP will not check if the file is locked unless you explicitly make a call.

The concept is almost identical to that of mutexes (protecting shared resources, etc.), but this is important enough for special attention.

+3
source share

All Articles