PHP script to delete thousands of .jpg images?

703 Views Asked by At

My weak shared web host doesn't support cron or perl and I often need to delete thousands of .jpg images from certain folders. The images are uploaded from webcams. I'm wondering if there is a simple app out there that can find all .jpg images recursively and delete them.

I need to be able to target only images in the following date format : 2011-10-19_00-29-06.jpg ... and only images older than 48 hours.

Apache 2.2.20 DirectAdmin 1.39.2 MySQL 5.1.57 Php 5.2.17

4

There are 4 best solutions below

8
On

or just with php:

<?php

$last_2_days_in_seconds = 3600 * 48;

foreach (glob("*.jpg") as $filename) {
  if((time() - fileatime($filename)) > $last_2_days_in_seconds && preg_match('/^2011/', $filename)) unlink($filename);
}
?>
1
On

A simple naiive version:

$yesterday = date('Y-m-d', strtotime('yesterday')); // 2011-10-17
$day_before = date('Y-m-d', strtotime('2 days ago')); // 2011-10-16

$images = glob('*.jpg');

foreach($images as $img) {
    if (strpos($img, $yesterday) === 0) || (strpos($img, $day_before) === 0)) {
        continue;
    }
    unlink($img);
}

This will delete all files which are date-stamped 3 days or older, by checking if the file is date stamped yesterday or day-before-yesterday. But it will also delete all files created today.

A better version would be:

$images = glob("*.jpg");
foreach ($images as $img) {
     $ctime = filectime($img);
     if ($ctime < (time() - 86400 * 2)) {
         unlink($img);
     }
}

This version checks the actual last-modified time on the file, and deletes anything older than 48 hours. It will be slower, however, as the stat() call performed by filectime() will be a non-cheap call.

0
On

Something like this should get you started:

class MyRecursiveFilterIterator extends RecursiveFilterIterator {
    const EXT = '.jpg';
    public function accept() {
        // code that checks the extension and the modified date
        return $this->current()->getFilename() ...
    }
}

$dirItr    = new RecursiveDirectoryIterator('/sample/path');
$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr       = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);

// to iterate the list
foreach ($itr as $filePath => $fileInfo) {
    echo $fileInfo->getFilename() . PHP_EOL;
}
0
On

@user427687, Do you mean all the picture format 2011***.jpg? if so, may be my code would work.

<?php
  $path = dirname(__FILE__).'/filepath';
  if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ((time()-filectime($path.'/'.$file)) < 86400*2) {
          if (preg_match('/\2011(.*?).jpg$/i', $file)) {
            unlink($path.'/'.$file);
          }
          if (preg_match('/\2011(.*?).jpeg$/i', $file)) {
            unlink($path.'/'.$file);
          }
        }
    }
  }
?>