Current Location: Home> Latest Articles> PHP filemtime() Function Explained: How to Get the Last Modified Time of a File

PHP filemtime() Function Explained: How to Get the Last Modified Time of a File

M66 2025-07-09

Overview of filemtime()

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.

Function Syntax

<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.

Parameter Description

  • $filename: The name or full path of the file whose modification time you want to retrieve.

Return Value

  • Returns the last modified time as an integer timestamp if the file exists and is accessible.
  • Returns false if the file does not exist or is unreadable.

Code Example

<?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!";
}
?>

Code Explanation

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.

Best Practices and Notes

  • Always check if the file exists with file_exists() before calling filemtime() to avoid potential errors.
  • The function returns a raw Unix timestamp, which should be formatted with date() for readability.
  • When working cross-platform, ensure file paths are compatible with the server's operating system.

Conclusion

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.