我如何得到文件创建日期?

我正在读一个文件夹,里面有很多文件。

我如何得到一个文件的创建日期。我没有看到任何直接函数得到它。

filemtimefilectime

如果文件没有被修改,会发生什么?

166945 次浏览

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.

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.


$filename = 'somefile.txt';


if (file_exists($filename)) {


echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

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);
}
}