Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have written scripts that check images in a folder and in a database, I need to delete images in a folder that are not in the database. How do I do this?

1.

   $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);
       }
   }
  1. $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);
        }
    }
    

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

    $images_folder = __DIR__.'/assets/image/products/';
    
    $it = new RecursiveDirectoryIterator($images_folder);
    
    foreach (new RecursiveIteratorIterator($it) as $file) {
      if(!$file->isDir()  and  !in_array($file->getFileName(), array_column($listingsImages,'picture'))){
          $path_for_delete = $images_folder.$file->getFileName();
          unlink($path_for_delete);
      }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading