0

I am looking to create a script to use as a backup of my live server, it will run from a local PHP server and connect to a remote PHP server. looking around this can be done using PHP FTP.

Ideally the script starts at a given directory and then works its way through all the directories and files. It will create any directories that does not exist and copy any new files, ideally it ignores files that match, so not to copy the files again.

I have been working on this for a few days and so far can get a connection from the local server to the remove server, but after this i can not work out how to run through the directories and files and copy what is inside the starting directory.

I have tried to use RecursiveIteratorIterator to get a list of directories and files, but i can not get this to run, the code just seems to stop at this point.

$ftp_server = "ftp.servername.com";
$ftp_username = "username";
$ftp_password = "password";
$Localdir = "/Local-Copy";
$remote_dir = "Starting-Directory/";


$conn_id = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login_result = ftp_login($conn_id, $ftp_username, $ftp_password); //Login in with credentials

if ((!$conn_id) || (!$login_result)) { // If login fails
    echo "FTP Connection failed to server: $ftp_server for user $ftp_user_name <br>\r\n";
    exit;
} else {
    echo "Connected to Server $ftp_server, for user $ftp_username <br>\n";
}

ftp_pasv($conn_id, true); // Set Passive mode


$file_list = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($remote_dir )) as $filename) {
    if ($filename->isDir()) continue;
    $file_list[] = $filename;
}
print_r($file_list);
  • 1
    rsync/lsyncd might be a better task for this. It runs faster and is meant for this purpose – aynber Mar 27 '23 at 12:42
  • Is there any error? Does the line `print_r($file_list);` output an empty array? Note that it can take some time to run if you have a lot of files, maybe you can try to add a debug log inside the iterator loop to see if it's running? – Kaddath Mar 27 '23 at 12:44
  • `RecursiveDirectoryIterator` won't magically start working with files on FTP server, just because you have opened an FTP connection before. => See [PHP FTP recursive directory listing](https://stackoverflow.com/q/36310247/850848). – Martin Prikryl Mar 27 '23 at 12:47

0 Answers0