Finglish
Finglish

Reputation: 9956

How can I find when a folders content was last modified efficiently in php

I need to run a check on a folder to see when it was last modified. By this I mean the last time it, or any of the files it contains where last modified.

I have tried two ways so far:

  1. using the stat() function on the folder, and then grabbing mtime

    $stat = stat("directory/path/");
    echo $stat["mtime"];
    
  2. using the filemtime() function on the folder

    echo (filemtime("directory/path/"));
    

Both of these methods return the same value, and this value does not change if I update one of the files. I am guessing this is because the folder structure itself does not change, only the content of one of the files.

I guess I could loop through all the files in the directory and check their modification dates, but there are potentially a lot of files and this doesn't seem very efficient.

Can anyone suggest how I might go about getting a last modification time for a folder and its content in an efficient way?

Upvotes: 1

Views: 2419

Answers (1)

aksu
aksu

Reputation: 5235

moi.

I suggest that you loop all files using foreach function and use it, i think there's no function for that purpose. Here's very simple example using that loop:

$directory = glob('gfd/*');
foreach ($directory as $file) {
    $mdtime = date('d.m.Y H:i:s', filemtime($file));
}
echo "Folder last modified: $mdtime<br />"; 

Keep in mind that foreach is pretty fast, and if you have files < 3000, i think there's nothing to worried about. If you don't want to use this, you can always save modification date to file or something like that. :)

Subfolder-compatibility:

function rglob($pattern, $flags = 0) {
    $files = glob($pattern, $flags); 
     foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
         $files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags));
     }
     return $files;
}

See this question: php glob - scan in subfolders for a file

Upvotes: 2

Related Questions