Created
August 30, 2016 16:17
-
-
Save jonatanrdsantos/91e48f1cd83f4dc95d8fdefe17c069c7 to your computer and use it in GitHub Desktop.
Magento remove unused media catalog images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Avoid any time limit | |
set_time_limit(0); | |
// Avoid any memory limit | |
ini_set('memory_limit', -1); | |
// Include bootstrap code and Mage class | |
require_once 'app/Mage.php'; | |
// Enable developer mode | |
Mage::setIsDeveloperMode(true); | |
// Set the default file creation mask | |
umask(0); | |
// Init application with default store | |
Mage::app(); | |
$productImagesDir = realpath(Mage::getBaseDir('media') . '/catalog/product/'); | |
$ignoreDirs = array('cache', 'placeholder', '..', '.'); | |
$deletedFiles = 0; | |
// Get all used images from database | |
$magUsedImages = Mage::getSingleton('core/resource') | |
->getConnection('core_read') | |
->fetchAll( | |
'SELECT value FROM catalog_product_entity_media_gallery' | |
); | |
$magUsedImages = array_map(function($row) { | |
return $row['value']; | |
}, $magUsedImages); | |
$directory = new \RecursiveDirectoryIterator($productImagesDir, \FilesystemIterator::FOLLOW_SYMLINKS); | |
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) use ($magUsedImages) { | |
$ignoreDirs = array('cache', 'placeholder', '..', '.'); | |
// Skip hidden files and directories. | |
if ($current->getFilename()[0] === '.') { | |
return FALSE; | |
} | |
if ($current->isDir()) { | |
// Only recurse into intended subdirectories. | |
return !in_array($current->getFilename(), $ignoreDirs); | |
} | |
else { | |
// Only consume files of interest. - TRUE to get all images anyway | |
$name = $current->getPathname(); | |
if (!is_bool(strpos($name, '/catalog/product'))){ | |
$name = substr($name, strpos($name,'/catalog/product')+strlen('/catalog/product')); | |
} | |
return !in_array($name, $magUsedImages); | |
} | |
}); | |
$iterator = new \RecursiveIteratorIterator($filter); | |
$unusedMedia = array(); | |
foreach ($iterator as $info) { | |
$unusedMedia[] = $info->getPathname(); | |
} | |
foreach ($unusedMedia as $item) { | |
echo "removendo {$item}<br>"; | |
unlink($item); | |
// confirm if was real deleted | |
if (!is_file($item)) { | |
echo "Duplicated image deleted: {$item} <br><br> "; | |
} else { | |
echo "Fail to delete image: {$item}<br><br>"; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment