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 !!!
To upload and download files using PHP FTP, we just need to enable the FTP extension in php.ini and use it accordingly: That should cover the basics, but let us walk through a few actual examples in this guide – Read on! ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything…
ftp_get () retrieves a remote file from the FTP server, and saves it into a local file. An FTP\Connection instance. The local file path (will be overwritten if the file already exists). The remote file path. The transfer mode. Must be either FTP_ASCII or FTP_BINARY . The position in the remote file to start downloading from.
This is only tested on the Filezilla FTP server and PHP 8. If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world…
We use the ftp_connect () function to connect to an FTP server. Next, log in to the FTP server using the ftp_login () function. Then download the required files using ftp_get (). Finally, remember to close the FTP connection using ftp_close ().
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With