Backend Development 3 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Retrieve a File’s Last Modification Time in PHP

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

backendPHPDateTimestatfilemtime
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.