1

I'm trying to get the latest file with a specific extension from a folder via FTP. I'm using the following code to get the most recent file. But it gets the most recent file regardless of file extension.

// new connect

$conn = ftp_connect('ftp.website.com');
ftp_login($conn, 'username', 'password');

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

$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, "/home/mywebsite/public_html/wp-content/uploads/data-zipped/target.zip", $mostRecent\['file'\], FTP_BINARY);
ftp_delete($conn, $mostRecent\['file'\]);
ftp_close($conn);

I would like to get specific files with specific extensions.

The files I want to get end with the following filename.add.zip. The filename changes daily. So it could be file22.add.zip moredata.add.zip. But the add.zip remains the same.

Unfortunately there are also files with the extension filename.del.zip. So it can't just be .zip it needs to be add.zip.

So via FTP, I want to pickup the most recent file ending in add.zip.

Anyone have a solution? The code that I currently us only picks up the most recent file. Regardless of the file extension.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
PaulW32
  • 63
  • 4

2 Answers2

2

Apart from the good universal answer by @Anggara, many (most) FTP servers will simply allow you to retrieve listing filtered by the extension:

$files = ftp_nlist($conn, '/data/*.add.zip');

Some references:


Btw, if you have lots of files, calling php_mdtm for each of them might take ages. See also How to get last modified text files by date from remote FTP location.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • This solution is much better, since you don't have to list other files that does not match the pattern and will reduce the loop. – Anggara Nov 18 '22 at 09:20
1

If you want to check for files that ends with *.add.zip, add a filter in your loops:

foreach ($files as $file) {
    $time = ftp_mdtm($conn, $file);

    // get last 8 characters from the filename
    $fileSuffix = substr($file, -8);

    if ($time > $mostRecent['time'] && $fileSuffix == '.add.zip') {
        $mostRecent['time'] = $time;
        $mostRecent['file'] = $file;
    }
}

var_dump($mostRecent);
Anggara
  • 625
  • 4
  • 8
  • That works. But you definitely want to first filter the files by extension and only then query the remote server for the timestamp of the filtered files! – Martin Prikryl Nov 18 '22 at 07:27