How to sort files by modified date through php

ftp, php

Solution

If you only want to sort the files by last modified date, you can use

ftp_nlist($conn, '-t .');

This will not tell you what the date for each file is, though.

If you want to get the modified date as well, you can use `ftp_rawlist` and parse the output. Here's a quick example I scraped together:

$list = ftp_rawlist($ftp, '.');

$results = array();
foreach ($list as $line) {
    list($perms, $links, $user, $group, $size, $d1, $d2, $d3, $name) =
        preg_split('/\s+/', $line, 9);
    $stamp = strtotime(implode(' ', array($d1, $d2, $d3)));
    $results[] = array('name' => $name, 'timestamp' => $stamp);
}

usort($results, function($a, $b) { return $a['timestamp'] - $b['timestamp']; });

At this point `$results` contains a list sorted in ascending last modified time; reverse the sort function to get the list in most recently modified first format.

Note: `ftp_rawlist` does not provide exact modification timestamps, so this code might not always work accurately. You should also verify that the output from your FTP server agrees with this algorithm and include some sanity checks to make sure things stay that way in the future.

Problem

Background : I have a anonymous login ftp server, ftp_nlist only list files alphabetically, I would like to get the list of files on the basis of last modified date, recent first. I tried ftp_exec($conn, "ls -t") but I am presented with Permission Denied error, not sure why itsn't working. Well I am working with php-cli and the number of files are in thousands, I just want to work with recent files. Getting the raw list, and finding the date part of the array elements might help, but I hope there is easy way out. When I login via terminal command ls -t works just fine. So wondering why ftp_exec is not working. Seeking an easy suggestion. Thanks in advance.

Original source