Copying files

[copy](<http://php.net/copy>) copies the source file in the first argument to the destination in the second argument. The resolved destination needs to be in a directory that is already created.

if (copy('test.txt', 'dest.txt')) {
    echo 'File has been copied successfully';
} else {
    echo 'Failed to copy file to destination given.'
}

Copying directories, with recursion

Copying directories is pretty much similar to deleting directories, except that for files [copy](<http://php.net/copy>) instead of [unlink](<http://php.net/unlink>) is used, while for directories, [mkdir](<http://php.net/mkdir>) instead of [rmdir](<http://php.net/rmdir>) is used, at the beginning instead of being at the end of the function.

function recurse_delete_dir(string $src, string $dest) : int {
    $count = 0;

    // ensure that $src and $dest end with a slash so that we can concatenate it with the filenames directly
    $src = rtrim($dest, "/\\\\") . "/";
    $dest = rtrim($dest, "/\\\\") . "/";

    // use dir() to list files
    $list = dir($src);

    // create $dest if it does not already exist
    @mkdir($dest);

    // store the next file name to $file. if $file is false, that's all -- end the loop.
    while(($file = $list->read()) !== false) {
        if($file === "." || $file === "..") continue;
        if(is_file($src . $file)) {
            copy($src . $file, $dest . $file);
            $count++;
        } elseif(is_dir($src . $file)) {
            $count += recurse_copy_dir($src . $file, $dest . $file);
        }
    }

    return $count;
}

Renaming/Moving

Renaming/Moving files and directories is much simpler. Whole directories can be moved or renamed in a single call, using the [rename](<http://php.net/rename>) function.