How to get files in FTP folder sorted by modification time

There’s no standard way to have the FTP server sort the files according to your (or any) criteria.

Though some FTP servers, notably the ProFTPD and vsftpd, support proprietary flags with the LIST/NLST command to sort the entries.

Both these servers support the -t flag to sort the files by a modification time:

LIST -t

Though this is not only non-standard, it actually violates the FTP protocol.

For all options supported by ProFTPD, see its man page:
http://www.proftpd.org/docs/howto/ListOptions.html

Note that vsftpd supports only -a, -r, -t, -F and -l with the same meaning as ProFTPD.


If your server does not support the -t switch (or similar), your only option is to retrieve the listing with file attributes as is and sort it locally.

For this you cannot use ftp_nlist, as it returns file names only.

The ideal solution is to use the MLSD FTP command that returns a reliable machine-readable directory listing. But PHP supports that only since 7.2 with its ftp_mlsd function. Check the "modify" entry.

Or, there’s an implementation of the MLSD in user comments of the ftp_rawlist command:
https://www.php.net/manual/en/function.ftp-rawlist.php#101071

First check if your FTP server supports MLSD before taking this approach, as not all FTP servers do (particularly IIS and vsftpd don’t).

Or, you can use ftp_rawlist. Though it returns proprietary listing of files, that can be difficult to parse. But if you need to support one specific server only, you can hard code the parsing for that server.

Leave a Comment