Sort directory files by creation datetime in Windows filesystem
Asked Answered
T

2

3

How do I sort a directory by file creation, latest first in PHP 5.2?

I am on Windows 2000.

Tilton answered 18/1, 2010 at 9:29 Comment(0)
D
9

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.

Deacon answered 18/1, 2010 at 9:35 Comment(6)
This is modification Time not creation TimeTilton
Right. Did you read my first line? Most filesystems don't track creation time.Deacon
no, this won't work. rsort will lose the file names.Minni
@stcony0: I updated my answer to work with windows. Please note that it will not work with *nix.Deacon
+1 for using Spl - though iterators aren't known to be this fast either ;)Dalton
Yea, but they got some nice boosts in 5.3.Deacon
D
5

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.

Dalton answered 18/1, 2010 at 9:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.