Reputation: 504
I made a little script which allows me to download images from FTP server. But, the thing is, whenever I execute the script, ALL images are downloaded. Is there any way to rewrite the code so that it only downloads new images?
My script looks like this:
$ftp_server = "my_server_ip";
$ftp_user = "my_user_name";
$ftp_pass = "my_password";
$DIR="my_path_to_images_folder";
$conn = ftp_connect($ftp_server);
if(!$conn)
{
exit("Can not connect to server: $ftp_server\n");
}
if(!ftp_login($conn,$ftp_user,$ftp_pass))
{
ftp_quit($conn);
exit("Can't login\n");
}
ftp_chdir($conn,$DIR);
$files = ftp_nlist($conn,'.');
for($i=0;$i<count($files);$i++)
{
if(!ftp_get($conn,$files[$i],$files[$i],FTP_BINARY))
{
echo "Can't download {$files[$i]}\n";
}
else
{
echo "Successfully transferred images!";
}
}
ftp_quit($conn);
Thank you.
Upvotes: 1
Views: 1900
Reputation: 202262
To download only files that do not exist locally yet, or are newer than the local copy, use:
$files = ftp_nlist($conn, '.');
foreach ($files as $file)
{
$remote_time = ftp_mdtm($conn, $file);
if (!file_exists($file) ||
(filemtime($file) < $remote_time))
{
ftp_get($conn, $file, $file, FTP_BINARY);
touch($file, $remote_time);
}
}
If your server supports MLSD
command and you have PHP 7.2 and newer, you can replace ftp_nlist
and repeated call to ftp_mdtm
with one efficient call to ftp_mlsd
function.
See also How to get last modified text files by date from remote FTP location
Upvotes: 6
Reputation: 755
You can check image availability with method file_exists()
If this method return true, don't copy than file.
I guess you can modify script without my help :)
Upvotes: 2
Reputation: 6795
You'll need to define "new".
Write out to a log file the images that have been transferred, then next time the script runs you can lookup whats already been transferred and only transfer your "new" images (the ones not in the log file...)
Upvotes: 1