.htaccess – How to empty a directory in PHP except specific files

exception or error:

I’m creating a cron job that will autoflush the tmp directory everyday to make sure the tmp directory is not flooded with unwanted files.

However i want to delete all files and folders in the tmp directory except some files like .htaccess i’m using the below code, but is giving an error

    $filesToKeep = array(
                            '.htaccess'
                            // 'i.php',
                            // 'c.php'
                        );

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {
            if (! in_array($file, $filesToKeep))
                {
                    if ($file->isDir())
                        rmdir($file->getRealPath());
                }
            else
                unlink($file->getRealPath());
        }

Warning: rmdir(D:\Development(s)\Project(s)\blog\app\tmp\error_pages): Directory not empty

before this is used to run the below code which ran perfectly but also used to delete the .htaccess file

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {

            if ($file->isDir())
                rmdir($file->getRealPath());
            else
                unlink($file->getRealPath());
        }
How to solve:

Your error states that you can’t delete non-empty dir.

So just check if dir is empty first.

$filesToKeep = ['.htaccess', /*'i.php', 'c.php'*/];

$dir = '../tmp/';

$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

foreach ($files as $file) {
    if (in_array($file->getBasename(), $filesToKeep)) {
        continue;
    }

    if (!$file->isDir()) {
        unlink($file->getRealPath());
        continue;
    }

    if (isEmptyDir($file->getRealPath())) {
        rmdir($file->getRealPath());
    }
}

function isEmptyDir($dir){
    $files = scandir($dir);

    // $files contains `..` and `.` along with list of files
    return count($files) <= 2; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *