Skip to content

Instantly share code, notes, and snippets.

@devjosh12
Created February 10, 2015 10:00
Show Gist options
  • Save devjosh12/fdf9d4d6dc96ef90ed26 to your computer and use it in GitHub Desktop.
Save devjosh12/fdf9d4d6dc96ef90ed26 to your computer and use it in GitHub Desktop.
delete unused product images from server
<?php
require_once 'app/Mage.php';
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
echo "not exist";
} else {
//echo "exist";
}
$connection_read = Mage::getSingleton('core/resource')->getConnection('core_read');
$connection_write = Mage::getSingleton('core/resource')->getConnection('core_write');
/* $result = $connection_read->fetchAll('SELECT * FROM catalog_product_entity_media_gallery as mediagallery RIGHT OUTER JOIN catalog_product_entity as entitytable ON entitytable.entity_id = mediagallery.entity_id WHERE mediagallery.value is NULL');
if($result) {
//Zend_Debug::dump($result);
echo count($result) . ' products without images' . "\n";
}*/
$directory = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product';
if($directory){
$total = shell_exec('du -h ' . $directory);
$total = explode("\n",$total);
array_pop($total);
$total = array_pop($total);
$total = explode("\t",$total);
$total = array_shift($total);
$files = glob($directory . DS . '[A-z0-9]' . DS . '[A-z0-9]' . DS . '*');
//print_r($files);
$deleted = 0;
foreach($files as $file) {
$filename = DS . implode(DS,array_slice(explode(DS,$file),-3));
//echo "<br>";
//echo $filename."\n";
$results = $connection_write->fetchAll("SELECT * FROM catalog_product_entity_media_gallery WHERE value='".$filename."'");
if(count($results)==0) {
$filepath = Mage::getBaseDir('media') .'/catalog/product' . $filename ;
//unlink($filepath);
echo 'Deleting orphaned image ' . $filename . "\n";
$deleted++;
}
$total++;
}
echo "</br>";
echo 'Deleted ' . $deleted . ' of total ' . $total;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment