Magento 1.9 duplicate images being saved

by Raj Kumar   Last Updated June 21, 2018 15:09 PM

I am updating product's attributes and images through program. The problem is that, it is adding new images everytime and appending _1 or _1_1 to the file. Hence a lot of duplicate files in the drive.

I searched in the forum for the solution. They say not to save the product twice. You can see below code that I have a function downloadAndImportImage() that adds images and later on I save the product.

What am I missing ? Thanks in advance.

function downloadAndImportImage($image_url, $_product, $num, $sku){


        if (file_exists($filepath_to_image)) {
            $_product->addImageToMediaGallery($filepath_to_image, array('image', 'small_image', 'thumbnail'), false, false);

    }catch(Exception $e){
        echo $e->getMessage();

function updateProduct(){
    if ($record[14] != $record[13]){
       downloadAndImportImage($record[14], $_product, 14, $record[0]);
   if ($record[14] != $record[15]){
      downloadAndImportImage($record[15], $_product, 15, $record[0]);



Answers 1

You'd validate if current media values of product are the same as the ones you are trying to update. If same file exists Magento will append that _1 to filename to avoid overwriting files. This happens in lib/Varien/File/Uploader.php

static public function getNewFileName($destFile)
    $fileInfo = pathinfo($destFile);
    if (file_exists($destFile)) {
        $index = 1;
        $baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];
        while( file_exists($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $baseName) ) {
            $baseName = $fileInfo['filename']. '_' . $index . '.' . $fileInfo['extension'];
            $index ++;
        $destFileName = $baseName;
    } else {
        return $fileInfo['basename'];

    return $destFileName;

You can try changing that logic & use your custom method, rewriting _getNotDuplicatedFilename() method in Mage_Catalog_Model_Product_Attribute_Backend_Media class, which calls above function

Another way would be running some clean process after your update, and delete unused images. You have some examples here

Raul Sanchez
Raul Sanchez
June 28, 2018 06:01 AM

Related Questions

How can I add exception for image extension?

Updated March 13, 2017 09:09 AM

Images uploaded but not saved

Updated May 07, 2016 08:03 AM