Backend Development 4 min read

Using PHP filemtime to Retrieve File Modification Time

This article explains how to use PHP's filemtime function to obtain a file's last modification timestamp, demonstrates single‑file and multiple‑file examples with code, and shows how to format the timestamp using the date function.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP filemtime to Retrieve File Modification Time

The PHP function filemtime returns the last modification time of a file as a Unix timestamp when you pass the file path as an argument.

In PHP you can use it as follows:

$file_path = 'path/to/file.txt'; // file path
$modification_time = filemtime($file_path); // get last modification time

echo "文件最后修改时间:" . date('Y-m-d H:i:s', $modification_time); // convert timestamp to readable format

The code first defines a variable $file_path that should be replaced with the actual path of the file you want to inspect. The filemtime function is then called with this path to obtain the modification timestamp, and date formats the timestamp into a human‑readable date and time string.

Code Example 1: Get File Last Modification Time

$file_path = 'path/to/file.txt';
$modification_time = filemtime($file_path);

echo "文件最后修改时间:" . date('Y-m-d H:i:s', $modification_time);

In this example the file path is assumed to be path/to/file.txt ; you can change it to any valid path and use date with different format strings to output the timestamp as needed.

Code Example 2: Get Multiple Files' Last Modification Times

$files = array(
    'path/to/file1.txt',
    'path/to/file2.txt',
    'path/to/file3.txt'
);

foreach ($files as $file_path) {
    $modification_time = filemtime($file_path);
    echo "文件:'" . basename($file_path) . "' 最后修改时间:" . date('Y-m-d H:i:s', $modification_time) . "
";
}

This example defines an array $files containing several file paths, iterates over the array, retrieves each file's modification time with filemtime , obtains the file name using basename , and formats the timestamp with date for display.

Summary: The article demonstrates how to use PHP's filemtime function to obtain a file's last modification time, convert the resulting timestamp to a readable format with date , and provides practical code snippets for handling both single and multiple files.

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