Recursive Copy of Directory

前端 未结 14 984
花落未央
花落未央 2020-12-08 15:14

On my old VPS I was using the following code to copy the files and directories within a directory to a new directory that was created after the user submitted their form.

14条回答
  •  遥遥无期
    2020-12-08 15:28

    I have changed Joseph's code (below), because it wasn't working for me. This is what works:

    function cpy($source, $dest){
        if(is_dir($source)) {
            $dir_handle=opendir($source);
            while($file=readdir($dir_handle)){
                if($file!="." && $file!=".."){
                    if(is_dir($source."/".$file)){
                        if(!is_dir($dest."/".$file)){
                            mkdir($dest."/".$file);
                        }
                        cpy($source."/".$file, $dest."/".$file);
                    } else {
                        copy($source."/".$file, $dest."/".$file);
                    }
                }
            }
            closedir($dir_handle);
        } else {
            copy($source, $dest);
        }
    }
    

    [EDIT] added test before creating a directory (line 7)

提交回复
热议问题