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
815 views
in Technique[技术] by (71.8m points)

php - How to get last modified text files by date from remote FTP location

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 $value
";
    } else {
        echo "There was a problem
";
    }
}

I got success in getting text files, but not selecting the last modified files, filemtime is not helping me nor curl.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...