Home > Blockchain >  Retrieve newest file with a specific extension
Retrieve newest file with a specific extension

Time:11-18

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.

CodePudding user response:

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.

CodePudding user response:

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);
  • Related