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 converting it to a readable date with date(), and provides code examples for retrieving timestamps for a single file and multiple files.
The PHP function filemtime can be used to get a file's last modification time. It is simple: pass the file path as a parameter and the function returns a timestamp representing the file's last modification.
In PHP you can use filemtime 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 formatThe code first defines a file path variable $file_path which you should replace with the actual path of the file you want to check. Then filemtime is called with that path to obtain the timestamp, and date converts the timestamp to a human‑readable date‑time string.
Code Example‑1: Get a Single File's 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 we assume the file path is 'path/to/file.txt' . You can change the path as needed and use date to output the modification time in any desired format.
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 snippet defines an array $files containing several file paths, iterates over them, obtains each file's modification timestamp with filemtime , and prints the filename (using basename ) together with the formatted date.
Summary
The article introduces how to use PHP's filemtime function to retrieve a file's last modification time, returning a timestamp that can be formatted into a readable date with date . Code examples demonstrate retrieving timestamps for a single file and for multiple files.
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.