How do I download an FTP directory via php?

Asked

Viewed 129 times

0

Well I managed to download a specific file from my FTP via php , but I need to download an entire directory someone knows how to do this, already found example in PHP manual more anything!

my code to download a specific file

<?php

// define some variables
$local_file = 'teste.pdf';
$server_file = './teste/teste1.pdf';
$ftp_server="ftp.exemplo.com";
$ftp_user_name="usuariopedro";
$ftp_porta="22";
$ftp_user_pass="senhapedro";

$conn_id = ftp_ssl_connect($ftp_server,$ftp_porta);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// turn passive mode on
ftp_pasv($conn_id, true);

// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
}
else {
    echo "There was a problem\n";
}
// close the connection
ftp_close($conn_id);

?>
  • take care of addresses, usernames and password.

  • yes, they are an example

  • I added to the reply an example of how the files could be listed and the files downloaded.

1 answer

1

By the FTP protocol, there is no possibility to download a directory. Although this option exists in many programs, it is managed by the application itself. This is done by listing the directory files and downloading them one by one.

Here’s an example of how it could be done in PHP

// define some variables
$ftp_server="ftp.exemplo.com";
$ftp_user_name="usuariopedro";
$ftp_porta="22";
$ftp_user_pass="senhapedro";
$directory = ".";

$conn_id = ftp_ssl_connect($ftp_server,$ftp_porta);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// turn passive mode on
ftp_pasv($conn_id, true);

$files = ftp_nlist($conn_id, $directory);

foreach ($files as $file) { 
    if ($file == '.' || $file == '..') 
        continue; 

    ftp_get($conn_id, $file, $file, FTP_BINARY)
}

// close the connection
ftp_close($conn_id);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.