In this tutorial, we are going to show you 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 the inbuilt filemtime function.
This function will return the time in a Unix format.
Take a look at the following PHP example:
//The path to the file. $file = 'log.txt'; //Get the modification time using the filemtime function. //This function will return a Unix timestamp. $lastModifiedTimestamp = filemtime($file); //Convert the timestamp into a human-readable format //and then 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. This can be a full path or a relative path. In this case, we are trying to get the modification time of a file called “log.txt”
- We retrieved the time using PHP’s filemtime function. This function will return a Unix timestamp.
- Finally, we converted the timestamp into a human-readable format using the date function.
When we ran the code 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 Jan 01 1970?!
If filemtime is unable to find the last modification time, it will return a FALSE value.
If you pass a FALSE value into the date function, the end result will be similar to 01 Jan 1970 01:00:00.
This is because the function will treat FALSE values as 0.
In Unix, 0 is January 1st, 1970.
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? If it’s not working, try using the full path to the file instead of the relative path.
- Does your PHP script have permission to access this file?
The time on my file isn’t updating?
By default, PHP will cache the results of this function.
This is for performance reasons.
In order to force filemtime to return the latest modification time, you will need to call the clearstatcache function:
//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 is especially important if your PHP script needs to read the modification time multiple times.