Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anilbajracharya/e63495ae254da2d0bf026b2045944c56 to your computer and use it in GitHub Desktop.
Save anilbajracharya/e63495ae254da2d0bf026b2045944c56 to your computer and use it in GitHub Desktop.
duplicate product image issue magento 2
<?php
require '../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
echo $mediaPath;
$path = $mediaPath . DIRECTORY_SEPARATOR . "catalog" . DIRECTORY_SEPARATOR . "product";
$product_folder = array();
$di = new RecursiveDirectoryIterator($path);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
//echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
if (!is_dir($filename)) {
$folder_file = str_replace($mediaPath, '', $filename);
$folder_file = str_replace('\\', '/', $folder_file);
$product_folder[] = $folder_file;
}
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');
$categoryId = 41; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);
$categoryProducts = $category->getProductCollection()
->addAttributeToSelect('*');
$images_array = array();
foreach ($categoryProducts as $product) {
//print_r($product->getData());
// printing category name and url
//echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
$objectManager->get("Magento\Catalog\Model\Product\Gallery\ReadHandler")->execute($product);
$imageProcessor = $objectManager->create('\Magento\Catalog\Model\Product\Gallery\Processor');
$images = $product->getMediaGalleryImages();
foreach ($images as $child) {
$file_update = str_replace($mediaPath, "", $child->getPath());
$images_array[] = "/" . $file_update;
}
}
echo "<pre>";
print_r($images_array);
print_r($product_folder);
echo "</pre>";
foreach ($product_folder as $file) {
if (!in_array($file, $images_array)) {
if($_GET['action']=="run"){
unlink($mediaPath . $file);
}
echo "<br/>";
echo " Not found " . $file;
echo "<br/>";
} else {
echo "<br/>";
echo "--found " . $file;
echo "<br/>";
}
}
die("---27--");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment