简体   繁体   中英

How to empty a directory in PHP except specific files

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());
        }

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM