ProgrammerGirl
ProgrammerGirl

Reputation: 3223

How to delete all files in all sub-folders except those whose filename is 'whatever.jpg' in PHP?

What's the fastest way to delete all files in all sub-folders except those whose filename is 'whatever.jpg' in PHP?

Upvotes: 1

Views: 830

Answers (3)

Dreen
Dreen

Reputation: 7226

This should be what youre looking for, $but is an array holding exceptions. Not sure if its the fastest, but its the most common way for directory iteration.

function rm_rf_but ($what, $but)
{
    if (!is_dir($what) && !in_array($what,$but))
        @unlink($what);
    else
    {
        if ($dh = opendir($what))
        {
            while(($item = readdir($dh)) !== false)
            {
                if (in_array($item, array_merge(array('.', '..'),$but)))
                    continue;
                rm_rf_but($what.'/'.$item, $but);
            }
        }

        @rmdir($what); // remove this if you dont want to delete the directory
    }
}

Example use:

rm_rf_but('.', array('notme.jpg','imstayin.png'));

Upvotes: 1

Federkun
Federkun

Reputation: 36954

Why not use iterators? This is tested:

function run($baseDir, $notThis)
{
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
        if ($file->isFile() && $file->getFilename() != $notThis) {
            @unlink($file->getPathname());
        }
    }
}

run('/my/path/base', 'do_not_cancel_this_file.jpg');

Upvotes: 3

Ron
Ron

Reputation: 1336

Untested:

function run($baseDir) {
    $files = scandir("{$baseDir}/");
    foreach($files as $file) {
        $path = "{$badeDir}/{$file}";
        if($file != '.' && $file != '..') {
            if(is_dir($path)) {
                run($path);
            } elseif(is_file($path)) {
                if(/* here goes you filtermagic */) {
                    unlink($path);
                }
            }
        }
    }
}
run('.');

Upvotes: 0

Related Questions