1

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.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Nancy
  • 504
  • 2
  • 6
  • 21

3 Answers3

6

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

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
2

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 :)

Michail M.
  • 735
  • 5
  • 11
1

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...)

Stuart
  • 6,630
  • 2
  • 24
  • 40
  • «You'll need to define "new"» yes please, there is alot of 'new' file. => non-existing file,, file that has been modified since ,file newr that hte one you already have. – Louis Loudog Trottier Mar 27 '17 at 11:45