tags:

views:

110

answers:

3

I have a bit of script that deletes all .png files in a directory:

foreach (glob("*.png") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
    unlink($filename);
}

How do I take this one step further to delete all .png files over a certain file size?

I have another bit of script that finds out the file size of all the files in the directory:

$bytes = filesize('example.png');

How do I combine the two?

+3  A: 

You can use an if statement to check whether the size is above the threshold:

$threshold = 1024;

foreach (glob("*.png") as $filename) {
    $size = filesize($filename);
    if ($size > $threshold) {
        unlink($filename);
    }
}
Tom Haigh
Thanks for all your answers, guys. They all worked great!
baselinej70
+1  A: 
$maxsize = 1024; // example

foreach (glob("*.png") as $filename)
{
    $filesize = filesize($filename);
    echo "$filename size " .$filesize . "\n";
    if ($filesize > $maxsize)
        unlink($filename);
}
Michal M
A: 

You can also use the SPL iterators

<?php
$path = '.';
class MyFilter extends FilterIterator  {
    public function accept() {
     $fi = $this->getInnerIterator()->current();
     return strlen($fi)-4===strripos($fi, '.png') && 1024 < $fi->getSize();
    }

}
foreach (new MyFilter(new DirectoryIterator($path)) as $deleteInfo) {
    echo $deleteInfo, "\n";
}

(could be a bit more flexible ...but it's only an example)
If you want it to delete recursively take a look at the RecursiveDirectoryIterator

VolkerK