PHP Recursive copy/delete functions

27 June 2023 devTechnology
Share with:

In a recent project I needed quite often to delete or copy whole directories. And since PHP doesn’t seem to have such – I created these:

Remove Directory
protected function rmdir($path) : void
{
    if (is_dir($path)) {
        $children = scandir($path);
        foreach ($children as $child) {
            if ('.' === $child || '..' === $child) {
                continue;
            }
            $local_path = "{$path}/{$child}";

            if ("dir" === filetype($local_path)) {
                self::rmdir($local_path);
            } else {
                unlink($local_path);
            }
        }
        rmdir($path);
    }
}

Copy Directory
protected function cpdir($src, $dest) : void
{
    if (!is_dir($dest)) {
        mkdir($dest);
    }

    if (is_dir($src)) {
        $children = scandir($src);
        foreach ($children as $child) {
            if (in_array($child, ['.', '..'])) {
                continue;
            }

            $source = "{$src}/{$child}";
            $destination = "{$dest}/{$child}";

            if (is_dir($source)) {
                self::cpdir($source, $destination);
            } else {
                copy($source, $destination);
            }
        }
    }
}