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

did*_*ido 7 php ftp

在FTP服务器上有一些文件.对于此服务器上的任何小时,都要上传新文件.我想下载最后一个文件.如何从此服务器获取上次上传的文件?所有文件都有不同的名称.

我使用下面的脚本下载一个文件.

$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);
Run Code Online (Sandbox Code Playgroud)

提前致谢 !!!

Jam*_*bri 10

无法确定哪个文件是最新的,因为没有"上传时间"属性.您没有提及有关FTP服务器的更多信息,但如果您对上传有一定程度的管理,则可以确保在上载时设置上次修改时间.这最终是否起作用取决于您的FTP服务器以及可能的客户端.

假设您的修改时间等于上传时间,您可以执行以下操作:

// 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);
Run Code Online (Sandbox Code Playgroud)


小智 0

ftp_rawlist($conn);
Run Code Online (Sandbox Code Playgroud)

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