Snippet. PHP. Get the Last Modified Time of a Directory

The following PHP function returns the time, when a directory has last been modified. The function checks the each of the files in the directory and returns the last time any of the files has been changed. If needed the function can easily be modified to recursively check the child directories.

//======================== START OF FUNCTION ==========================//
// FUNCTION: dirmtime                                                  //
//=====================================================================//
   /**
    * Returns the last modified time of the directory
    * @param string $directory
    * @return int
    */
function dirmtime($directory) {
    // 1. An array to hold the files.
    $last_modified_time = 0;

    // 2. Getting a handler to the specified directory
    $handler = opendir($directory);

    // 3. Looping through every content of the directory
    while ($file = readdir($handler)) {
        // 3.1 Checking if $file is not a directory
        if(is_file($directory.DIRECTORY_SEPARATOR.$file)){
            $files[] = $directory.DIRECTORY_SEPARATOR.$file;
            $filemtime = filemtime($directory.DIRECTORY_SEPARATOR.$file);
            if($filemtime>$last_modified_time) {
                $last_modified_time = $filemtime;
            }
	}
    }

    // 4. Closing the handle
    closedir($handler);

    // 5. Returning the last modified time
    return $last_modified_time;
}
//=====================================================================//
//  FUNCTION: dirmtime                                                 //
//========================== END OF METHOD ============================//

Example

This example demonstrates how to find the last modified time of the directory, where the working PHP script file resides, and print the result to the screen.

$directory = dirname(__FILE__);

$dir_last_modified_time = dirmtime($directory);

echo date('d M Y h:i:s', $dir_last_modified_time);

Updated on: 23 Nov 2024