Stefan
Stefan

Reputation: 17

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?

Upvotes: 0

Views: 1017

Answers (1)

Jan
Jan

Reputation: 43169

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?

Upvotes: 1

Related Questions