Copy files to other server(ftp)

How to copy all files of a directory to a directory on other server ?
Suppose, we have to copy all files in a directory(dir/subdir) to other server directory(dir/sub) and we also have to create directory there(in case, if directory does not exist), then –

First of all make connection with Remote(other) FTP (from where we are copying the files) like –
$ftp_host = ‘host’;
$ftp_username = ‘ftp_username’;
$ftp_password = ‘ftp_password’;
$ftp_connection = ftp_connect($ftp_host);

Then, login to Remote or other ftp using –
$ftp_login = ftp_login($ftp_connection,$ftp_username,$ftp_password);

function isdir_ftp($ftp_connection,$dir){
$pushed = ftp_pwd($ftp_connection);
if($pushed!=false && @ftp_chdir($ftp_connection,$dir)){
ftp_chdir($ftp, $pushed);
return true;
}
return false;
}

Suppose, we have to copy the directory and files in public_html directory –
$server_path = “./public_html/”;
$file_path_server = “dir/subdir” ;
$server_file_path = $server_path. $file_path_server ;
$is_dir = isdir_ftp($ftp_connection, $file_path_server);
if(!$is_dir){
$dir = $file_path_server;
$dd = ”;
$d=explode(“,”,$dir);
for($i=0;$i<count($d);$i++){
$dd.=$d[$i].”/”;
//try to create dir
$dir = $dd;
$is_dir = isdir_ftp($ftp_connection, $dir);
if(!$is_dir){
if(ftp_mkdir($frp_connection, $dir)){
echo “Dir created successfully”;
}else{
echo “Error”;
}
}
}
}

Now read the files from local ftp from where we have to copy the files and the copy it –
$local_ftp_dir = ” dir/subdir “;
if ($handle = @opendir($ local_ftp_dir )) {
while (false !== ($file = readdir($handle))) {
if ($file != “.” && $file != “..”) {
$source= $ local_ftp_dir .’/’.$file;
$dest = “public_html/”.$ local_ftp_dir .’/’.$file;
$upload = ftp_put($ftp_connection, $dest, $source, FTP_BINARY);
if (!$upload) {
echo ‘FTP upload failed!’;
} else {
echo “uploaded successfully”;
}
}
}
}

ftp_close($ftp_connection);

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Leave a Reply

Your email address will not be published. Required fields are marked *