File creation time [closed]
How do I sort a directory by file creation, latest first in PHP 5.2?
I am on Windows 2000.
On windows the CTime is the creation time, use the following:
<?php
$files = array();
foreach (new DirectoryIterator('/path') as $fileInfo) {
$files[$fileInfo->getFileName()] = $fileInfo->getCTime();
}
arsort($files);
After this $files will contain an array of your filenames as the keys and the ctime as the values. I chose this backwards representation due to the possibility of identical ctimes, which would cause an entry in $files to be overwritten.
Edit:
Updated answer to use CTime as the OP clarified he's using Windows.
File creation time does not exist on most operating systems.
You can't for creation date on Unix system, but for change date, but see edit below for Windows.
Code is as follows:
function sortByChangeTime($file1, $file2)
{
return (filectime($file1) < filectime($file2));
}
$files = glob('*'); // get all files in folder
usort($files, 'sortByChangeTime'); // sort by callback
var_dump($files); // dump sorted file list
From the Notes on the PHP Manual on filectime:
Note: 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.
See the link in Antti's answers for the differences in ctime, atime and mtime and decide for your Usecase which is the most suited when you are on Unix.
Edit: one of the comments at the page for filectime notes that there is no change time on Windows and filectime indeed returns the creation time. I'm no pro on Windows Filesystems, but using the above is then probably your best bet. Alternatively, you can look into the COM API to get a handle on the ScriptingHost and see if you can get the Creation Time from there.
精彩评论