PHP: Get the last modification time of a file.

This is a tutorial on how to get the last modification time of a file using PHP. To get the time and date that a file was created or last modified, we can use PHP’s filemtime function. This function will return the modification time in a Unix format.

Take a look at the following PHP example:

In the code above, we:

  1. Specified the path to the file that we want to get the modification date of. This can be a full path or a relative path. In this case, I am trying to get the modification time of a file called “log.txt”
  2. We got the modification time of the file using PHP’s inbuilt filemtime function. This function returns the modification time in a Unix format.
  3. Finally, we converted this Unix timestamp into a human-readable format using PHP’s date function.

When I ran the PHP snippet above, the result was as follows:

log.txt was last modified on 09 Jan 2020 11:43:19

Perfect!

The modification time for my file is 01 Jan 1970?!

If filemtime is unable to find the last modification time, it will return a FALSE value. If a FALSE value gets passed into PHP’s date function, the end result will be similar to 01 Jan 1970 01:00:00. This is because false will be treated as 0 and 0 in Unix is the 1st of January, 1970.

OK, so why is filemtime returning FALSE?

If filemtime is returning FALSE, then you need to check the following:

  1. Does the file actually exist?
  2. Is the path to the file correct? Try using the full path to the file instead of the relative path.
  3. Does your PHP script have permission to access this file?

The modification time on my file isn’t updating?

The results of filemtime are automatically cached by PHP for performance reasons. In order to force filemtime to return the latest modification time, you will have to call the clearstatcache function like so:

This can be especially important for PHP scripts that read the last modification time of a particular file multiple times.

Facebook Comments