Search code examples
phplinuxcachingcache-controlprocess

PHP flock function limitations and txt cache files


I have a fairly basic PHP script that caches data to a text file. I need to come up with a solution that prevents two running instances of the script from writing to the file at the same time. I've looked into the PHP flock function, however, the PHP manual (http://php.net/manual/en/function.flock.php) mentioned one big limitation:

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

I've got two questions regarding this warning that I'm hoping someone can answer. First, how can I check if my implementation of flock is done at the process level or not? Btw, I'm running CentOS, with cPanel.

Second, if my implementation is at the process level, does that mean that one running instance of my script will not be aware of a lock done by another running instance of the same script? Or do script instances run on separate threads and not separate processes? Any clarification about this is very much appreciated.

Thanks.


Solution

  • The only common case would be running Apache, with the some kind threaded (non-forking) npm. 99% of the cases you are not running PHP threaded.. it's a relatively safe assumption.

    Aside from that, it may be worth trying to avoid locking..

    The biggest issue you have is that 2 processes may be writing at the same time, or 1 process reads the cache when it's not fully generated. The easiest way to get around this, is to let the PHP script generate the cache in a different file in a temporary location. When the file is written, just move it into place (with rename()). File moves are guaranteed to be atomic when it's happening on the same mount.