Magento remove images of deleted products

Clean up not used Magento images

Magento unfortunately does not remove images of a product unfortunately if the product is removed. The following script checks all the images and checks if it’s still present in the database of Magento. If not, it deletes the image. Use the following code:


$mageFilename = 'app/Mage.php';
require_once $mageFilename;

ini_set('display_errors', 1);



$media = Mage::getBaseDir('media').'/catalog/product';

echo "Query database for images …\n";
$query = "SELECT value FROM catalog_product_entity_media_gallery";
$data = Mage::getSingleton('core/resource')->getConnection('core_read')->fetchAll($query);

foreach($data as $item){

echo "Images found in database:".count($dbData)."\n";

echo "Search images in media directory …\n";
$images = findFiles($media, array('jpg'));
echo "Images found under directory ($media):".count($images['jpg'])."\n";

echo "Start removing images …\n";
foreach($images['jpg'] as $image) {
    //echo "Skip cached image : $image\n";

  $imageCleanup = str_replace($media,"",$image);
    echo "Skip image is in database : $image\n";
    echo "Remove image : $image\n";
    //if($testrun==false) unlink($image);

echo "Done, removed $removedCount images and skipped $skippedCount images.\n";

function findFiles($directory, $extensions = array()) {
  function glob_recursive($directory, &$directories = array()) {
    foreach(glob($directory, GLOB_ONLYDIR | GLOB_NOSORT) as $folder) {
      $directories[] = $folder;
      glob_recursive("{$folder}/*", $directories);
  glob_recursive($directory, $directories);
  $files = array ();
  foreach($directories as $directory) {
  foreach($extensions as $extension) {
  foreach(glob("{$directory}/*.{$extension}") as $file) {
  $files[$extension][] = $file;
return $files;


Clean up Magento space: could save a lot of GBs

In my case, I tried the script for a store with 40K images of which 10K were not used. This is a disk space reduction of a few Gigabytes.

Final word

This script is thanks to a comment on RapidCommerce. If you use the script, that’s on your own responsibility. Try it out on a staging server and make a backup in advance. Cheers!

Load normal product price instead of indexed product price

Would you like to ignore the indexed product price in the templates (for example in catalog/product/list.phtml where the indexed price is used)?

Then go to: catalog/product/list.phtml


<?php echo $this->getPriceHtml($product) ?>


<?php $product = Mage::getModel( 'catalog/product' )->load($_product->getId()); ?>
<?php echo $this->getPriceHtml($product) ?>

There are two occurrences in list.phtml, so don’t forget to replace it twice. Only do this when it’s the only solution of displaying right prices, since loading the product takes extra time, compared to loading the indexed product price.