In PHP development, retrieving the last modified time of a file is a common requirement. The filemtime() function is designed for exactly this purpose. It returns the Unix timestamp of a file's last modification, making it useful for file monitoring, cache validation, and more.
<span class="fun">int filemtime ( string $filename )</span>
This function takes a single argument — the path to the file, which can be either relative or absolute. It returns the last modification time as a Unix timestamp. If the file does not exist or cannot be read, it returns false.
<?php
$file = './test.txt'; // Set the file path to check
if (file_exists($file)) {
$lastModifiedTime = filemtime($file); // Get the file's last modified time
echo "File last modified: " . date("Y-m-d H:i:s", $lastModifiedTime);
} else {
echo "File does not exist!";
}
?>
In this example, a relative file path ./test.txt is used. To prevent errors when the file doesn't exist, the file_exists() function is used to check for its existence before calling filemtime().
If the file is found, filemtime() retrieves its last modified timestamp. Then, date() is used to convert the timestamp into a human-readable format, which is output using echo.
filemtime() is a useful PHP function for accessing a file’s last modification time. It plays a key role in scenarios like caching, file syncing, and version control. Combined with file_exists() and date(), it helps build reliable and efficient file handling mechanisms.
Mastering filemtime() will enhance your capabilities in PHP file operations and overall application performance.