I am stuck on atomization of an process to download last modified text files on date wise or today. Here is my code.
$conn_id = ftp_connect($ftp_server); $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); $contents = ftp_nlist($conn_id, '-rt .'); reset($contents); function is_txt($file) { return preg_match('/.*.txt/', $file) > 0; } $filtered = array_filter($contents, is_txt); // download all files in downloaded directory while (list($key, $value) = each($filtered )) { if (ftp_get($conn_id, $dir.'\downloaded\'.$value, $value, FTP_BINARY)) { echo "Successfully written to $valuen"; } else { echo "There was a problemn"; } }
I got success in getting text files, but not selecting the last modified files, filemtime
is not helping me nor curl.
Advertisement
Answer
Since PHP 7.2, you can use ftp_mlsd
function to retrieve list of files including their timestamps. Check the "modify"
entry. You can then easily identify the latest file.
With older versions of PHP, you will need to use the ftp_mdtm
function to retrieve the modification time of files.
But you have to call it individually for every file, what is pretty inefficient.
You can also try 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).
The only other way is to use the ftp_rawlist
function. But its returns a ls
-like line for every file with no pre-defined format. If you connect to one specific server, you can use it; and hard-code the parsing based on the specifics of the server. But it’s not reliable, if you need to connect to an arbitrary server.
Typical listing on a *nix server is like:
drwxr-x--- 3 vincent vincent 4096 Jul 12 12:16 public_ftp drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 public_html -rwxrwxrwx 1 vincent vincent 11 Jul 12 12:16 file.txt
For some basic code, see PHP FTP recursive directory listing – That that does not include the timestamp parsing.