PHP filemtime(): Get the Last Modified Time of a File

The PHP filemtime() function is used when we need to find the last time the file was modified. For example:

<?php
   echo "<p>The latest time when the file <b>codescracker.txt</b> was modified:</p>";
   echo filemtime("codescracker.txt");
   echo "<br>Or<br>";
   echo date("d F, Y H:i:s", filemtime("codescracker.txt"));
?>

The output produced by the above PHP example using the filemtime() function is:

php filemtime function

Since the filemtime() function returns the last modified time and date of the file in a Unix timestamp, that almost cannot be understood by a normal user. Therefore, let me use the date() function to convert the time into a format that a normal user can understand.

<?php
   $file = "codescracker.txt";
   echo "<p>The file, $file last modified on:</p>";
   
   $mt = filemtime($file);
   if($mt)
   {
      echo "Time: " .date("H:i:s", $mt);
      echo "<br>";
      echo "Date: " .date("d F, Y", $mt);
   }
   else
      echo "Unable to find time, when the file last modified!";
?>

Now the output produced by the above PHP example should be:

php filemtime function example

PHP filemtime() Syntax

The syntax of the filemtime() function in PHP is:

filemtime(filename)

The function filemtime() returns False on failure.

A frequent application of the filemtime() function is to determine whether a file has been modified since its last access. You can use this function, for instance, to determine if a cache file has expired and must be regenerated.

Advantages of the filemtime() function in PHP

Disadvantages of the filemtime() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!