9

On FTP server has some files. For any hour on this server is uploading new files. I'd like to download last file. How can I get last uploaded file from this server? All files are with different names.

I used folowing script to downloading one file.

$conn = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn,"user","pass");
ftp_get($conn,"target.txt","source.txt",FTP_ASCII);
ftp_close($conn);

Thanks in advance !!!

Nemoden
  • 8,816
  • 6
  • 41
  • 65
dido
  • 2,330
  • 8
  • 37
  • 54
  • Tried anything? Explain step by step what you think the solution is (like 1. Get list of files, 2. Find newest file) and show where you are stuck. – CodeCaster Apr 17 '13 at 08:34
  • I always work with a `proceed` folder, there I move the files that I downloaded with ftp. This keeps you from checking on time stamps – S.Visser Apr 17 '13 at 08:43

2 Answers2

14

There is no way to be sure which file is the most recent, as there is no such thing as an "uploaded time" attribute. You didn't mention much about the FTP server, but if you have some level of management over the uploads, you could ensure that the last modified time is set on upload. Whether this ends up working is down to your FTP server and possibly clients.

Assuming your modified times are equivalent to upload times, you could do something like this:

// connect
$conn = ftp_connect('ftp.addr.com');
ftp_login($conn, 'user', 'pass');

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

$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, "target.txt", $mostRecent['file'], FTP_ASCII);
ftp_close($conn);
Jamie Schembri
  • 6,047
  • 4
  • 25
  • 37
0
ftp_rawlist($conn);

extract latest filename and get it.

Maik
  • 11
  • 1
  • this is actually a pretty solid solution. you have to do some string magic and crunching but it WILL find the newest file, no matter the file names – clockw0rk Oct 11 '22 at 22:51