Use PHP to connect to FTP and backup all folder contents
I'm building a custom web app that stores the FTP and MySQL settings for the websites I manage for clients. My goal is not only to store the settings for reference, but to create functionality to assist in doing regular backups.
I've got the MySQL backup functio开发者_开发问答nality working great, as it connects to the remote databases, creates a dump and sends it to my browser to download locally.
BUT... what is the best way to connect to a remote FTP and download all the contents of a specific folder to my local computer?
Any suggestions would be amazing!
This example from the php manual posted by mroerick might help you.
<?php
$ftp_server = "ftp.example.com";
$conn_id = ftp_connect ($ftp_server)
or die("Couldn't connect to $ftp_server");
$login_result = ftp_login($conn_id, "user", "pass");
if ((!$conn_id) || (!$login_result))
die("FTP Connection Failed");
ftp_sync (".");
ftp_close($conn_id);
function ftp_sync ($dir) {
global $conn_id;
if ($dir != ".") {
if (ftp_chdir($conn_id, $dir) == false) {
echo ("Change Dir Failed: $dir<BR>\r\n");
return;
}
if (!(is_dir($dir)))
mkdir($dir);
chdir ($dir);
}
$contents = ftp_nlist($conn_id, ".");
foreach ($contents as $file) {
if ($file == '.' || $file == '..')
continue;
if (@ftp_chdir($conn_id, $file)) {
ftp_chdir ($conn_id, "..");
ftp_sync ($file);
}
else
ftp_get($conn_id, $file, $file, FTP_BINARY);
}
ftp_chdir ($conn_id, "..");
chdir ("..");
}
?>
精彩评论