#66 - Function to unlink a directory with files

Date: 2019-06-22 12:00 - PHP

PHP util function to remove directory with files recursively.

<?php
class Utils {
    private static function unlinkDir($dirname) {
        $dh = dir($dirname);
        while (($fileName = $dh->read()) !== false) {
            $file = $dirname . $fileName;
            if ($fileName == '.' || $fileName == '..')
                continue;
            if (is_dir($file))
                static::unlinkDir($file . '/');
            else
                unlink($file);
        }
        $dh->close();
        rmdir($dirname);
    }

    public static function unlink($filename) {
        if (!file_exists($filename))
            return;
        if (is_dir($filename))
            static::unlinkDir($filename . '/');
        else
            unlink($filename);
    }
}

Previous snippet | Next snippet