'How do I delete images that are not used in the database?

I have written scripts that check images in a directory and in a database. I need to delete images in a directory that are not in the database.

How can I do this?

   $listingsImages = $this->db->query("SELECT picture FROM product_")->row_array();

   $cwd = './assets/image';
   $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($cwd), RecursiveIteratorIterator::SELF_FIRST );


   foreach ( $iterator as $path ) {
       if(!$path->isFile()) continue;
       $dirname = explode("/",$path->__toString());
       $dirname = substr($dirname[count($dirname)-2], 0, 1);
       if ($dirname === ".") continue;
       if (substr($path->getFilename(), 0, 1) === ".") continue;

       if ($path->isDir()) {
           print($path->__toString() . "<br>");
       } else {
           print($path->__toString() . "<br>");
       }
   }

   foreach ($filenames as $filename) {
       if (!in_array($filename, $listingsImages)) {
           unlink($filename);
       }
   }

   $listingsImages = $this->db->query("SELECT picture FROM product_")->row_array();
   //pull out the paths of all used images from the database

   $it = new RecursiveDirectoryIterator(base_url('/assets/image/products')); // path to the image folder

   foreach (new RecursiveIteratorIterator($it) as $file) { // go through the folder and pull out the paths to all the files
       $filenames[] =$file->getPathname() . "\n";
   }

   foreach ($filenames as $filename) {
       if (!in_array($filename, $listingsImages)) {
           unlink($filename);
       }
   }


Solution 1:[1]

You are closer than you think, correct your second script:

$arrImagesFromDB = ['S97A2501.JPG','ikra.JPG'];

$images_folder = './assets/image/products';

$it =  new DirectoryIterator($images_folder); 

foreach ($it as $file) {
    if(!$file->isDot() and !$file->isDir() and !in_array($file->getFilename(),$arrImagesFromDB)){
        unlink( $file->getPathname());
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1