I am reading a folder with lots of files.
How can I get the creation date of a file. I don't see any direct function to get it.
There are filemtime
and filectime
.
And if the file hasn't been modified, what will happen?
Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).
Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
There is a solution for Mac OS X which supports date creation time in its file system: How do I get actual creation time for a file in PHP on a Mac?
I know this topic is super old, but, in case if someone's looking for an answer, as me, I'm posting my solution.
This solution works IF you don't mind having some extra data at the beginning of your file.
Basically, the idea is to, if file is not existing, to create it and append current date at the first line.
Next, you can read the first line with fgets(fopen($file, 'r'))
, turn it into a DateTime
object or anything (you can obviously use it raw, unless you saved it in a weird format) and voila - you have your creation date! For example my script to refresh my log file every 30 days looks like this:
if (file_exists($logfile)) {
$now = new DateTime();
$date_created = fgets(fopen($logfile, 'r'));
if ($date_created == '') {
file_put_contents($logfile, date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
}
$date_created = new DateTime($date_created);
$expiry = $date_created->modify('+ 30 days');
if ($now >= $expiry) {
unlink($logfile);
}
}
来源:https://stackoverflow.com/questions/4401320/php-how-can-i-get-file-creation-date