Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

php - How to get files in FTP folder sorted by modification time

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...