简体   繁体   中英

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

I would like to connect to a FTP Server via PHP and take the most recent file from a certain directory and show it in that PHP file.

So I can go to www.domain.com/file.php and see what's in that file. These files have the following name "Filename_20150721-085620_138.csv" , so the second value 20150721 is the actual date. Also these files only contain CSV Text.

Is there any way to achieve this?

Welcome to Stackoverflow! Consider the following code and explanation:

// 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);

Afterwards your $newestfile holds the most recent filename. Is this what you were after?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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