How to Safely Delete Product Image Cache Using the OpenMage Image Cleaner Extension

Run the "Sync Product Cache" routine to identify orphaned cache files whose original product images no longer exist, then delete the recorded entries via the admin grid to purge only stale cache files from media/catalog/product/cache while leaving all original images in media/catalog/product intact.

The OpenMage Image Cleaner extension provides a secure mechanism for managing product image cache in Magento and OpenMage environments. By distinguishing between generated cache files in media/catalog/product/cache and original assets stored in media/catalog/product, the extension ensures that cleanup operations target only disposable thumbnails and resized variants without risking data loss.

Detecting Orphaned Product Image Cache Files

The extension identifies stale cache entries through the syncproductCacheAction() method in app/code/community/Fballiano/ImageCleaner/controllers/Adminhtml/FbimagecleanerController.php. This process compares every file in the cache directory against its corresponding original asset.

Scanning the Cache Directory

The detection workflow begins by establishing the filesystem boundaries. The controller defines the cache folder at media/catalog/product/cache and the original product media folder at media/catalog/product. Using the helper method scandirRecursive() from Fballiano_ImageCleaner_Helper_Data, the system recursively enumerates every file within the cache directory tree.

Validating Against Original Images

For each cached file discovered, the code reconstructs the expected path of the original image by extracting the last three path segments. It then verifies whether that original file exists in the non-cache directory using file_exists(). If the original is missing, the cache file is flagged as orphaned.

Placeholders are explicitly excluded from processing through a path check that skips any file containing /placeholder/.

Recording Orphaned Entries

Orphaned entries are stored in the fb_imagecleaner_image table with a negative entity type identifier:

$entity_type_id = -Mage::getModel('catalog/product')->getResource()->getTypeId();
$db->insert($cleaner_table, ['entity_type_id'=>$entity_type_id,'path'=>$unused_image]);

This negative value distinguishes cache entries from original assets and preserves the full filesystem path for subsequent deletion.

Executing Safe Deletion of Cache Files

Once orphaned cache files are cataloged, the extension provides two administrative mechanisms to remove them physically from the server without affecting original assets.

Single File Deletion

The deleteAction() method handles individual cache file removal. It retrieves the specific record from the database, uses Helper::getMediaDirByEntityTypeId() to resolve the correct base media directory (which returns catalog/product/ for product entities), constructs the absolute filesystem path by appending the stored relative path, and executes unlink() to delete the file. Finally, it removes the database entry to maintain consistency.

Bulk Deletion

For larger cleanup operations, massDeleteAction() processes an array of selected image IDs. It iterates through each ID, applying the same path resolution and unlink() logic as the single deletion method, allowing administrators to purge hundreds of stale cache files in a single operation.

Both methods strictly operate on paths derived from the cache detection phase, ensuring that only files within media/catalog/product/cache are targeted, while the original media/catalog/product files remain untouched.

Programmatic Usage and Automation

Developers can trigger the cache cleanup process programmatically without using the admin interface. The following PHP script demonstrates how to execute the detection routine and subsequently delete all identified orphaned cache files:

// 1. Trigger the sync to populate the database table
Mage::getModel('adminhtml/url')
    ->setRoutePath('adminhtml/fbimagecleaner/syncproductCache')
    ->getUrl();

// 2. Retrieve all detected orphaned product cache entries
$resource = Mage::getSingleton('core/resource');
$db = $resource->getConnection('core_write');
$cleanerTable = $resource->getTableName('fb_imagecleaner_image');
$entityTypeId = -Mage::getModel('catalog/product')->getResource()->getTypeId();

$rows = $db->fetchAll(
    $db->select()
        ->from($cleanerTable, ['image_id', 'path'])
        ->where('entity_type_id = ?', $entityTypeId)
);

// 3. Delete each orphaned cache file safely
$helper = Mage::helper('fballiano_imagecleaner');
$mediaDir = $helper->getMediaDirByEntityTypeId($entityTypeId);

foreach ($rows as $row) {
    $fullPath = $mediaDir . $row['path'];
    if (file_exists($fullPath) && unlink($fullPath)) {
        $db->query("DELETE FROM {$cleanerTable} WHERE image_id = ?", $row['image_id']);
    }
}

This script mirrors the admin panel functionality exactly, first identifying orphaned files via the sync routine, then removing only those specific cache entries while preserving all original product images.

Core Source Files Reference

The following table maps the key components of the product image cache cleanup functionality to their source locations in the fballiano/openmage-image-cleaner repository:

File Purpose Location
FbimagecleanerController.php Contains syncproductCacheAction(), deleteAction(), and massDeleteAction() for detection and deletion workflows app/code/community/Fballiano/ImageCleaner/controllers/Adminhtml/FbimagecleanerController.php
Data.php Helper class providing scandirRecursive() and getMediaDirByEntityTypeId() for filesystem operations app/code/community/Fballiano/ImageCleaner/Helper/Data.php
Grid.php Adminhtml block rendering the grid of orphaned cache images app/code/community/Fballiano/ImageCleaner/Block/Adminhtml/Fbimagecleaner/Grid.php
config.xml Module configuration defining the fb_imagecleaner_image table and model setup app/code/community/Fballiano/ImageCleaner/etc/config.xml

Summary

  • The OpenMage Image Cleaner extension identifies orphaned product image cache files by comparing entries in media/catalog/product/cache against existing originals in media/catalog/product.
  • The syncproductCacheAction() method performs the detection, storing results in the fb_imagecleaner_image table with a negative entity type identifier to distinguish cache entries.
  • Deletion occurs through deleteAction() or massDeleteAction(), which resolve file paths using Helper::getMediaDirByEntityTypeId() and remove only the targeted cache files via unlink().
  • Original product images remain completely untouched because the validation logic specifically excludes the non-cache media directory from deletion operations.
  • Developers can automate the process programmatically by triggering the sync routine followed by database-driven file deletion using the provided helper methods.

Frequently Asked Questions

Will deleting product image cache affect my original product images?

No. The extension specifically targets files located in media/catalog/product/cache and its subdirectories. During the detection phase, syncproductCacheAction() verifies that the corresponding original file in media/catalog/product does not exist before flagging a cache entry for deletion. The deletion methods only remove files that have been pre-validated as orphaned cache entries, ensuring original assets remain intact.

What happens if I delete a cache file that is still in use?

The extension prevents this scenario through its two-step workflow. Files are only presented for deletion after syncproductCacheAction() confirms their original source image is missing from the filesystem. If a cache file is currently referenced by an existing product image, the validation logic (file_exists() check on the original path) will exclude it from the deletion grid, making accidental removal of active cache files impossible through the standard UI.

Can I automate the product image cache cleanup process?

Yes. Developers can programmatically trigger the detection routine by invoking the syncproductCacheAction() controller logic, then execute deletion by querying the fb_imagecleaner_image table for entries with the negative product entity type ID. Using the Fballiano_ImageCleaner_Helper_Data::getMediaDirByEntityTypeId() method to resolve paths and unlink() to remove files, you can safely automate cache purging via cron jobs or deployment scripts without manual admin interaction.

How does the extension distinguish between cache and original files?

The extension uses directory path analysis and entity type identification. Original product images reside in media/catalog/product/, while cached variants are stored in media/catalog/product/cache/. The syncproductCacheAction() method specifically scans the cache subdirectory, then reconstructs the expected original file path by extracting the last three path segments and verifying existence in the non-cache directory. Additionally, the database uses negative entity type IDs (specifically -Mage::getModel('catalog/product')->getResource()->getTypeId()) to mark records as cache entries rather than original assets.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →