Search code examples
phpmysqlunlinkfilemtime

How to Delete few older images using php?


I want to delete images from a specific category that are older than a certain age (say, 2 months).

These images are located in directory somewhere, if I use the following code:

<?php

// define the directory
$dir = "images/";

// cycle through all files in the directory
foreach (glob($dir."*") as $file) {

    // if file is 2 Month (5.184e+6 seconds) old then delete it
    if (filemtime($file) < time() - 5.184e+6) {
        unlink($file);
    }
}

?>

Then it deletes all 2 month old images, but I want to delete images by category.

This is a table in my database:

------------------------------------
table msn_story_images
------------------------------------
ID    image(url)   thumbnail   sortstyID

The images folder is pretty large (around 19GB), and can't be listed on the server.


Solution

  • OK, so you're saving only the image URL in the database. I guess you can have a logical relation between db images and file system images by the images' name. I would suggest to get the relevant images from the DB first of all, and put them into a flat array containing only the URLs. Go through the array and convert the image names to omit the leading URL part. A simplified example:

    foreach($imagesWithUrl as $idx => $image) {
      $imagesWithUrl[$idx] = basename($image);
    }
    

    Then, in your loop, check for existance of this image in the array coming from DB:

    /*** cycle through all files in the directory ***/
    foreach (glob($dir."*") as $file) {
    
      /*** if file is 2 Month (5.184e+6 seconds) old then delete it ***/
      if (filemtime($file) < time() - 5.184e+6 && in_array(basename($file), $imagesWithUrl)) {
          unlink($file);
      }
    }