如何删除数据库中未使用的图像



我已经编写了检查目录和数据库中图像的脚本。我需要删除数据库中没有的目录中的图像。

我该怎么做?

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

你比你想象的更接近,纠正你的第二个脚本:

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

相关内容

  • 没有找到相关文章

最新更新