Skip to content

Instantly share code, notes, and snippets.

@Flyingmana
Created May 29, 2015 12:23
Show Gist options
  • Save Flyingmana/e699fe336fa7d6617e0e to your computer and use it in GitHub Desktop.
Save Flyingmana/e699fe336fa7d6617e0e to your computer and use it in GitHub Desktop.
<?php
/**
*
*
* src of remove script: http://www.codefuel.co.uk/magento-removing-media-that-doesnt-belong-to-products/
*
*/
require_once __DIR__.'/../abstract.php';
/**
*
*
* @category Mage
* @package Mage_Shell
*/
class Mage_Shell_Clean_Unused_Product_Images extends Mage_Shell_Abstract
{
/**
* Run script
*
*/
public function run()
{
/** @var Varien_Db_Adapter_Pdo_Mysql $readConnection */
$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$sImgDir = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product';
$sMediaTbl = Mage::getSingleton('core/resource')->getTableName('catalog_product_entity_media_gallery');
$i=0;
$oIterator = new RecursiveDirectoryIterator($sImgDir);
foreach( new RecursiveIteratorIterator($oIterator) as $sFile) {
// filepath has cache as part, or is a directory, then jump to next one and do nothing.
if(strpos($sFile, "/cache") !== false || is_dir($sFile) ) {
continue;
}
$sFilePath = str_replace($sImgDir, "", $sFile);
$sQuery = "SELECT value FROM $sMediaTbl WHERE value= ?";
$sValue = $readConnection->fetchOne($sQuery,array($sFilePath));
if($sValue == false){
echo "## REMOVEING: " . $sFilePath . " ## \n";
//unlink($sFile);
$i++;
}
}
echo "\r\n\r\n Finished removing $i un-used product images\r\n\r\n";
}
}
$shell = new Mage_Shell_Clean_Unused_Product_Images();
$shell->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment