How to get files in FTP folder sorted by modificat

2019-01-15 17:08发布

问题:

I want to get all files in a FTP folder with ftp_nlist function.

But by default it returns an array sorted by name.

I want to sort them by last modified time. I tried to add -lt before a folder path, but it just add date time before each file name.

Please help me!

回答1:

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/directives/linked/config_ref_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.

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.

If you need a generic solution, an ideal way is to use the MLSD FTP command that returns a reliable machine-readable directory listing. But PHP does not support that.

There's an implementation of the MLSD in user comments of the ftp_rawlist command:
https://secure.php.net/manual/en/function.ftp-rawlist.php#101071



标签: php ftp