Reputation: 3223
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
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
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
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