Recursive Copy of Directory

前端 未结 14 1001
花落未央
花落未央 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:40

    There were some issues with the functions that I tested in the thread and here is a powerful function that covers everything. Highlights:

    1. No need to have an initial or intermediate source directories. All of the directories up to the source directory and to the copied directories will be handled.

    2. Ability to skip directory or files from an array. (optional) With the global $skip; skipping of files even under sub level directories are handled.

    3. Full recursive support, all the files and directories in multiple depth are supported.

    $from = "/path/to/source_dir";
    $to = "/path/to/destination_dir";
    $skip = array('some_file.php', 'somedir');
    
    copy_r($from, $to, $skip);
    
    function copy_r($from, $to, $skip=false) {
        global $skip;
        $dir = opendir($from);
        if (!file_exists($to)) {mkdir ($to, 0775, true);}
        while (false !== ($file = readdir($dir))) {
            if ($file == '.' OR $file == '..' OR in_array($file, $skip)) {continue;}
            
            if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
                copy_r($from . DIRECTORY_SEPARATOR . $file, $to . DIRECTORY_SEPARATOR . $file);
            }
            else {
                copy($from . DIRECTORY_SEPARATOR . $file, $to . DIRECTORY_SEPARATOR . $file);
            }
        }
        closedir($dir);
    }
    

提交回复
热议问题