Php – How to check if directory contents has changed with PHP


I'm writing a photo gallery script in PHP and have a single directory where the user will store their pictures. I'm attempting to set up page caching and have the cache refresh only if the contents of the directory has changed. I thought I could do this by caching the last modified time of the directory using the filemtime() function and compare it to the current modified time of the directory. However, as I've come to realize, the directory modified time does not change as files are added or removed from that directory (at least on Windows, not sure about Linux machines yet).

So my questions is, what is the simplest way to check if the contents of a directory have been modified?

Best Answer

As already mentioned by others, a better way to solve this would be to trigger a function when particular events happen, that changes the folder. However, if your server is a unix, you can use inotifywait to watch the directory, and then invoke a PHP script.

Here's a simple example:

inotifywait --recursive --monitor --quiet --event modify,create,delete,move --format '%f' /path/to/directory/to/watch |
  while read FILE ; do
    php /path/to/trigger.php $FILE

See also: