Skip to content

Instantly share code, notes, and snippets.

@kelvysmoura
Last active February 26, 2025 15:09
Show Gist options
  • Save kelvysmoura/19b3ac6fe1ce85897549e1204021e45a to your computer and use it in GitHub Desktop.
Save kelvysmoura/19b3ac6fe1ce85897549e1204021e45a to your computer and use it in GitHub Desktop.
MAGENTO 2 - REMOVE UNEUSED PRODUCT IMAGES
<?php
# MAGENTO 2 - REMOVE UNEUSED PRODUCT IMAGES
# copy into magento_path/var
require dirname(__DIR__, 1) . '/app/bootstrap.php';
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\State;
use Magento\Framework\Registry;
use Magento\Framework\App\ResourceConnection;
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$execute = function (array $nsList, callable $callable) use ($objectManager) {
$objects = array_map(fn($ns) => $objectManager->get($ns), $nsList);
$callable(...$objects);
};
$execute([
State::class,
ResourceConnection::class
], function($state, $resourceConnection){
$connection = $resourceConnection->getConnection();
$productMediaPath = dirname(__DIR__, 1) . '/pub/media/catalog/product';
$glob = glob("{$productMediaPath}/*/*/*.*");
$glob = array_map(function($file) use ($productMediaPath) {
return str_replace($productMediaPath, '', $file);
}, $glob);
$mediaGallery = $connection->fetchCol("SELECT value FROM catalog_product_entity_media_gallery");
$mediaGalleryVarchar = $connection->fetchCol("SELECT value FROM catalog_product_entity_varchar WHERE attribute_id IN (260, 263, 533, 266, 269)");
$allSavedMedias = array_unique(array_merge($mediaGallery, $mediaGalleryVarchar));
$filesToExclude = array_diff($glob, $allSavedMedias);
echo "Total files on storage: " . count($glob) . "\n";
echo "Total file on database: " . count($allSavedMedias) . "\n";
echo "Total files that not on database: " . count($filesToExclude) . "\n";
echo "Total on table catalog_product_entity_media_gallery: " . count($mediaGallery) . "\n";
echo "Total on table catalog_product_entity_varchar: " . count($mediaGalleryVarchar) . "\n\n";
sleep(10); // time to regret
$deletedPath = dirname(__DIR__, 1) . '/pub/media/backup_deleted_images';
foreach ($filesToExclude as $file) {
$pathInfo = pathinfo($deletedPath . $file);
exec("mkdir -p {$pathInfo['dirname']}");
exec("mv {$productMediaPath}{$file} " . $pathInfo['dirname']);
echo "Deleted {$file} \n";
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment