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:
//The path to the file that you want to get //the last modified time and date of. $file = 'log.txt'; //Get the last modified time using the filemtime function. //This function will return a Unix timestamp. $lastModifiedTimestamp = filemtime($file); //Convert the timestamp into a human-readable format //and print it out. $lastModifiedDatetime = date("d M Y H:i:s", $lastModifiedTimestamp); echo "$file was last modified on $lastModifiedDatetime";
In the code above, we:
- 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”
- We got the modification time of the file using PHP’s inbuilt filemtime function. This function returns the modification time in a Unix format.
- 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
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:
- Does the file actually exist?
- Is the path to the file correct? Try using the full path to the file instead of the relative path.
- 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:
//Clear the file status cache clearstatcache(); //Get the last modified time using the filemtime function. //This function will return a Unix timestamp. $lastModifiedTimestamp = filemtime($file);
This can be especially important for PHP scripts that read the last modification time of a particular file multiple times.