How to Retrieve a File’s Last Modification Time in PHP
This article explains how to retrieve a file’s last modification time in PHP using functions like filemtime(), stat(), and the DateTime class, and provides a practical example for detecting changes and notifying users.
Getting a file’s last modification time is useful for tracking updates or determining when a file needs to be reloaded. In PHP there are several ways to obtain this timestamp.
Using filemtime() function
The filemtime() function is the simplest method; it returns the Unix timestamp of the given file since January 1, 1970.
$timestamp = filemtime('file.txt');Using stat() function
The stat() function returns an array containing information about the file, including the modification time.
$result = stat('file.txt');
$timestamp = $result['mtime'];Using DateTime object
You can use the DateTime object to obtain the file’s last modification time; the object can parse timestamps.
$timestamp = filemtime('file.txt');
$date = new DateTime();
$date->setTimestamp($timestamp);
echo $date->format('Y-m-d H:i:s');Practical example
Assume you have a file named file.txt and you want to notify the user when the file has changed since it was last read.
The following demonstrates using filemtime() to achieve this:
$last_modified = filemtime('file.txt');
if ($last_modified > $_SESSION['last_read']) {
// File has been modified
echo 'File has been updated!';
$_SESSION['last_read'] = $last_modified;
}Java learning material
C language learning material
Frontend learning material
C++ learning material
PHP learning material
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
