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);
}
}
-
$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); } }
CodePudding user response:
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);
}
}