How to copy and paste a folder and its contents on a vps using ftp php

I want to copy & paste a folder and its contents in my vps. my code is below :

$conn = ftp_connect("my_ip_address");
ftp_login($conn, "username", "password"); 
$src = "/var/www/src_folder"; 
$dst = "/var/www/dst_folder"; 
ftp_exec($conn, "cp -r $src $dst"); 
if(ftp_exec($conn, "cp -r $src $dst")) echo "success copy"; 
ftp_close($conn);

but my results is ftp_exec(): Unknown SITE command.

1 answer

  • answered 2022-05-04 11:23 Chris

    You cannot copy directly via FTP - there's no valid command for it. These are the available commands.

    If you must use FTP (vs. SSH for example), then I believe your best option is to download the file and then upload it to the copy destination.

    For example, if you were just dealing with a single file or empty directory, you could do something like this:

    $local_temp_file = sys_get_temp_dir() . '/tmpfile';
    ftp_get($conn, $local_temp_file, $src_file);
    ftp_put($conn, $dst_file, $local_temp_file);
    unlink($local_temp_file);
    

    However, since you are dealing with a folder with all its contents, that adds additional complexity - you will need to recursively transfer all folder contents in the same manner - both when downloading and when uploading.

    You can put together a solution by referencing answers on these other posts:

    Or, you can use a library to simplify the problem a bit - for example, https://github.com/Nicolab/php-ftp-client, which has "putAll" and "getAll" methods that will help you with directories.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum