title: How do I delete images that are not used in the database?
body: <p>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.</p>
  <p>How can I do this?</p>
  <pre><code>   $listingsImages = $this-&gt;db-&gt;query(&quot;SELECT picture FROM product_&quot;)-&gt;row_array();
  
     $cwd = './assets/image';
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($cwd), RecursiveIteratorIterator::SELF_FIRST );
  
  
     foreach ( $iterator as $path ) {
         if(!$path-&gt;isFile()) continue;
         $dirname = explode(&quot;/&quot;,$path-&gt;__toString());
         $dirname = substr($dirname[count($dirname)-2], 0, 1);
         if ($dirname === &quot;.&quot;) continue;
         if (substr($path-&gt;getFilename(), 0, 1) === &quot;.&quot;) continue;
  
         if ($path-&gt;isDir()) {
             print($path-&gt;__toString() . &quot;&lt;br&gt;&quot;);
         } else {
             print($path-&gt;__toString() . &quot;&lt;br&gt;&quot;);
         }
     }
  
     foreach ($filenames as $filename) {
         if (!in_array($filename, $listingsImages)) {
             unlink($filename);
         }
     }
  </code></pre>
  <hr />
  <pre><code>   $listingsImages = $this-&gt;db-&gt;query(&quot;SELECT picture FROM product_&quot;)-&gt;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-&gt;getPathname() . &quot;\n&quot;;
     }
  
     foreach ($filenames as $filename) {
         if (!in_array($filename, $listingsImages)) {
             unlink($filename);
         }
     }
  </code></pre>