05 April 2014

Magento: Delete unused product images

Magento media folder grows all the time. It collects many unused files, such as abandoned product images. I've found that we already reached 100GB of product images on one from our Magento projects and decided to clean it.

I looked for magento extensions capable to search for unused / abandoned product images and delete them. For instance, following extension works great, but it fails on catalog with more than 100k products: Magento Connect - Image Clean
It died in close to infinite loop of 500k files info scanning. After that, it would try to put all it to DB and only then render some user interface, which had to allow me to run cleaup procedure. I was limited in time, couldn't wait 10 hours for result and wrote own script, which is 1000% more efficient and works on any magento installation. In theory it should support all magento versions starting from CE 1.5

Idea is very simple:

  1. Dump all product image files from database:
    SELECT `value` FROM catalog_product_entity_media_gallery;

  2. Select list of files from magento/media/catalog/product/ excluding cache folder:
    cd /var/www/magento/media/catalog/product/
    find ? -type f

  3. Compare first to second list, find files unique for file system and remove them.

You can find final version of script here: clean-gallery-images.sh

You'll need to change values of constants at start of script and it's ready to be used. I also added different validations and count-back to be able to cancel dangerous operation at last minute. The script was successfully used on production environment. It removed more than 140k images; it resulted in freeing 45GB of disk space.

Keep your Magento clean! :)


  1. Thanks for a very useful script. One small improvement - I had a issue when deleting images which start with a '-'. This can be fixed by changing the line:-

    rm -f $f


    rm -f "./$f"

    1. Tx for finding this typo. Fixed in Bitbucket.

    2. I don't see this fix in Bitbucket - https://bitbucket.org/andrey-legayev/misc/src/8b17939e01bfcc87bc9b71a0d73b1b3403dba419/magento/scripts/clean-gallery-images.sh?at=master&fileviewer=file-view-default . Or you use another location?

    3. Your URL is correct. The fix is in line #100, commit # 8b17939

  2. Thanks for script. It's very needed thing. I found one small error. When I entered wrong database name all images was deleted. I got only message "
    Loading list of gallery images from DB...
    ERROR 1049 (42000): Unknown database 'magento'
    0 files
    " and all images deleted. I added code "exit 1" to row 50 that not happens again

  3. For Magento here is the extension