How to Get File Last Modified Time in PHP using filemtime
This article explains how to use the built-in PHP function
filemtime() to determine the exact time a file was last
modified. You will learn the basic syntax of the function, how to format
the returned Unix timestamp into a human-readable date, and how to clear
the file status cache to ensure you always get accurate, real-time
results.
Basic Syntax of filemtime()
The filemtime() function accepts a single parameter—the
path to the file—and returns the file’s last modification time as a Unix
timestamp (the number of seconds since January 1 1970 00:00:00 GMT). If
the function fails, it returns false.
$filename = 'document.txt';
if (file_exists($filename)) {
$timestamp = filemtime($filename);
echo "Unix Timestamp: " . $timestamp;
} else {
echo "The file does not exist.";
}Formatting the Timestamp into a Readable Date
Because Unix timestamps are difficult for humans to read, you should
pair filemtime() with the PHP date() function
to format the timestamp into a readable date and time string.
$filename = 'document.txt';
if (file_exists($filename)) {
$timestamp = filemtime($filename);
// Format the timestamp (e.g., "October 24 2023 14:30:15.")
$readable_date = date("F d Y H:i:s.", $timestamp);
echo "The file was last modified on: " . $readable_date;
}Handling PHP File Stat Caching
PHP caches the results of file status functions, including
filemtime(), to improve performance. If a file is modified
during the execution of a script, calling filemtime() again
might still return the old modification time.
To prevent this and force PHP to look up the actual current
modification time on the disk, use the clearstatcache()
function before calling filemtime().
$filename = 'document.txt';
// Clear the cache to ensure accurate results
clearstatcache();
if (file_exists($filename)) {
$timestamp = filemtime($filename);
echo "Accurate Last Modified: " . date("Y-m-d H:i:s", $timestamp);
}