user2238083 user2238083 - 3 months ago 9
PHP Question

PHP delete multiple images types in a folder

I'm sure this is quite simple but I've had no luck getting the correct syntax. What's a better way to write multiple extensions? Or is this way (below) as good as any?

<?php
//Delete all image files in this folder
$path = 'files/';

if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if (filectime($file)< (time() - 2419200)) {
if (preg_match('/\.png$/i', $file)) {
unlink($path.'/'.$file);
}
if (preg_match('/\.jpg$/i', $file)) {
unlink($path.'/'.$file);
}
if (preg_match('/\.tif$/i', $file)) {
unlink($path.'/'.$file);
}
if (preg_match('/\.gif$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>

Answer
$extensions = array ('png', 'jpg', 'tif', 'gif'); // add any other extensions to this array

foreach ($extensions as $extension) {
    foreach (glob ($path . '/*.' . $extension) as $file) {
        if (filectime ($file) < (time () - 2419200)) {
            unlink ($file);
        }
    }
}
Comments