How to upload the latest file to FTP using PHP?

There are several files on the FTP server. During any hour, new files are uploaded to this server. I want to download the latest file. How can I download the last downloaded file from this server? All files have different names.

I used a script to upload a single 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!

+5
source share
2 answers

It is not possible to verify which file is the most recent, because there is no such thing as the "uploaded time" attribute. You didn't mention anything about the FTP server, but if you have some level of control over the downloads, you can make sure that the latest time change is set at boot time. Regardless of whether this works with your FTP server and possibly with clients.

, , - :

// 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);
+7
ftp_rawlist($conn);

.

-1

All Articles