开发者

PHP: how can I get file creation date?

开发者 https://www.devze.com 2023-01-29 12:49 出处:网络
I am reading a folder with lots of files. How can I get the creation date of a file. I开发者_如何学Python don\'t see any direct function to get it.

I am reading a folder with lots of files.

How can I get the creation date of a file. I开发者_如何学Python 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.


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消