Hi! This PHP tutorial is intended for beginners and it will teach you how to get the last modified date and time of a file. PHP is a powerful programming language and provides native functions to handle file system effectively. These file handling functions let you easily access the properties of files and one such property is ‘Last Modified Date’. This property stores the recently modified date and time of a file and we’ll see how to read this last-modified property of a file using php.
PHP Code to Get the Last Modified Date & Time of a File
There is a php function filemtime()
which returns the last modified time of a given file in Unix timestamp. You can use it like this,
<?php $file = "example.txt"; echo @date('F d, Y, H:i:s', filemtime($file)); ?> // produces output // September 10, 2015, 10:26:21
The method filemtime()
returns unix timestamp which we can format using the date() function to make it human readable.
The statement date('F d, Y, H:i:s', filemtime($file))
format and returns the last-modified timestamp according to the format string provided as the first parameter.
Note: You have to provide the filename with absolute path to filemtime(), if the file is located somewhere else other than the current working folder.
Get the Last Modified Date of All the Files in a Directory
Following the similar method you can easily get the last-modified date of entire files in a directory/folder. Here is the php code snippet to do that.
<?php $path = "D:/Images"; $fp = opendir($path); while ($file = readdir($fp)) { if ($file != "." && $file != "..") { echo basename($file) . " Last Modified On " . @date('F d, Y, H:i:s', filemtime($path . "/" . $file)) . "<br/>"; } } closedir($fp); ?> // produces output // image001.jpg Last Modified On October 16, 2015, 19:16:25 // image002.jpg Last Modified On October 15, 2015, 22:41:22 // image003.jpg Last Modified On October 20, 2015, 20:41:19 // image004.jpg Last Modified On October 16, 2015, 21:13:56 // image005.jpg Last Modified On October 17, 2015, 22:41:16
The methods opendir()
, readdir()
& closedir()
open, read and close the given directory respectively.
The statement basename($file)
returns only the absolute filename excluding the file path.
Also Read: PHP Form Validation using Regular Expression
Don’t Miss: Autocomplete Textbox using HTML5, PHP & MySQL
Likewise, you can easily get the last modified date and time of any files using native php functions.
No comments:
Post a Comment