PHP:通过FTP打开并显示文件夹中的最新文件


PHP: Open and show the most recent file from a folder via FTP

我想通过PHP连接到FTP服务器,并从某个目录中获取最新的文件,并将其显示在该PHP文件中。

所以我可以转到www.domain.com/file.php并查看该文件中的内容。这些文件的名称如下"Filename_20150721-085620_138.csv",因此第二个值20150721是实际日期。此外,这些文件仅包含CSV文本。

有什么办法做到这一点吗?

欢迎使用Stackoverflow!考虑以下代码和解释:

// connect
$conn = ftp_connect('ftp.addr.com');
ftp_login($conn, 'user', 'pass');
// get list of files on given path
$files = ftp_nlist($conn, '');
$newestfile = null;
$time = 0;
foreach ($files as $file) {
    $tmp = explode("_", $file);     // Filename_20150721-085620_138.csv => $tmp[1] has the date in question
    $year = substr($tmp[1], 0, 4);  // 2015
    $month = substr($tmp[1], 4, 2); // 07
    $day = substr($tmp[1], 6, 2);   // 21
    $current = strtotime("$month/$day/$year"); // makes a timestamp from a string
    if ($current >= $time) { // that is newer
        $time = $current;
        $newestfile = $file;
    }
}
ftp_close($conn);

之后,您的$newestfile会保存最新的文件名。这就是你想要的吗?