简体   繁体   English

如何使用PHP下载FTP上的最新文件?

[英]How can I download the most recent file on FTP with PHP?

On FTP server has some files. 在FTP服务器上有一些文件。 For any hour on this server is uploading new files. 对于此服务器上的任何小时,都要上传新文件。 I'd like to download last file. 我想下载最后一个文件。 How can I get last uploaded file from this server? 如何从此服务器获取上次上传的文件? All files are with different names. 所有文件都有不同的名称。

I used folowing script to downloading one file. 我使用下面的脚本下载一个文件。

$conn = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn,"user","pass");
ftp_get($conn,"target.txt","source.txt",FTP_ASCII);
ftp_close($conn);

Thanks in advance !!! 提前致谢 !!!

There is no way to be sure which file is the most recent, as there is no such thing as an "uploaded time" attribute. 无法确定哪个文件是最新的,因为没有“上传时间”属性。 You didn't mention much about the FTP server, but if you have some level of management over the uploads, you could ensure that the last modified time is set on upload. 您没有提及有关FTP服务器的更多信息,但如果您对上传有一定程度的管理,则可以确保在上载时设置上次修改时间。 Whether this ends up working is down to your FTP server and possibly clients. 这最终是否起作用取决于您的FTP服务器以及可能的客户端。

Assuming your modified times are equivalent to upload times, you could do something like this: 假设您的修改时间等于上传时间,您可以执行以下操作:

// connect
$conn = ftp_connect('ftp.addr.com');
ftp_login($conn, 'user', 'pass');

// get list of files on given path
$files = ftp_nlist($conn, '');

$mostRecent = array(
    'time' => 0,
    'file' => null
);

foreach ($files as $file) {
    // get the last modified time for the file
    $time = ftp_mdtm($conn, $file);

    if ($time > $mostRecent['time']) {
        // this file is the most recent so far
        $mostRecent['time'] = $time;
        $mostRecent['file'] = $file;
    }
}

ftp_get($conn, "target.txt", $mostRecent['file'], FTP_ASCII);
ftp_close($conn);
ftp_rawlist($conn);

提取最新的文件名并获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM