PHP FTP 复制目录递归


PHP FTP copy directory recursive

对于我的网站,我需要将一个文件夹从VPS上的主帐户复制到(自动)新创建的cPanel帐户。我尝试使用以下代码(函数)通过FTP使用PHP执行此操作:

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); 
        }
    }
    foreach (glob("*") as $file)
    {
        if(substr_count($file, ".") > 0)
        {
            $source_file = $file;
            $destination_file = $file;
            $upload = ftp_put($conn_id, "public_html/".$destination_file, $source_file, FTP_BINARY);
            echo "<br />";
            // check upload status
            if (!$upload) { 
                echo "FTP upload has failed!";
            } else {
                echo "Uploaded $source_file to $ftp_server as $destination_file";
            }
        }else{
            ftp_sync($dir);
        }
    } 

    ftp_chdir ($conn_id, "..");
        chdir ("..");  
} 

但是它似乎不起作用(没有创建新目录并上传到)...有谁知道为什么这不起作用以及我如何让它工作?

提前感谢!

此致敬意天辉。

编辑:我忘了提到我作为cronjob脚本运行脚本,并确保它在从主服务器执行时具有所有权限。

首先,确保目标服务器上的目录是可写的。暂时将其修改为 0777 应该会有所帮助。脚本的其余部分似乎还可以。您可以尝试将错误日志记录设置为所有错误(只需在脚本开头添加error_reporting(E_ALL);)。然后,PHP 应该输出每个错误、警告或通知,这可能会为您提供更多信息。

没有让函数工作,所以我以自己的方式重新创建了它并让它工作!

...
ftp_mkdir($conn_id, "public_html/".$dir);
ftp_upload($dir);
// close the FTP stream 
ftp_close($conn_id); 
function ftp_upload($dir) {
    global $conn_id;
    if($handle = opendir($dir))
    {
    while(false !== ($file = readdir($handle)))
    {
        if($file != "." && $file != ".." && $file != "...") {
        if(substr_count($file, ".") > 0)
        {
            $full_dir = "public_html/".$dir;
            $source_file = $file;
            $destination_file = $file;
            $upload = ftp_put($conn_id, $full_dir."/".$destination_file, $dir."/".$source_file, FTP_BINARY);
            echo "<br />";
            // check upload status
            if (!$upload) { 
                echo "FTP upload has failed!"; 
            } else {
                echo "Uploaded ".$source_file." to ".$ftp_server." as ".$destination_file; 
            }
        }else{
            ftp_mkdir($conn_id, "public_html/".$dir."/".$file);
            ftp_upload($dir."/".$file);
        }
        }
    }   
    }
}

现在唯一剩下的就是确保它也适用于大型目录结构(没有巨大的加载时间)!