Magento: Image upload script

Hey all, been a long time since I posted anything since my job is keeping me pretty busy…. here’s something I implemented for that might come in useful for you.

It’s a little script that basically scans a directory for images and, if it finds any, adds them to the relevant products.

Images have to be named as follows:




here’s the script.  Drop it into your ‘shell’ directory and run it on a cronjob then just upload your images as and when required.

	$image_dir = "full/path/to/image/upload/directory/";

	//add images to array

	$search = "*-*.jpg";
	$images = glob($image_dir.$search);
	$image_array = array();
	foreach($images as $image){
		$filename = strtoupper($image);
		$name = basename($filename);
		$dat = explode("-",$name);
		$sku = $dat[0];
		$imagenum = explode(".",$dat[1]);
		$imagenum = $imagenum[0];
		$image_array[$sku][$imagenum] = $image;
	if (count($image_array >= 1)){
		$output = "";
		foreach ($image_array as $sku=>$images){
			if (isset($images[1])){
				$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
				if ($product){
					$imgnum = 0;
					foreach($images as $image){
						$image_attributes = null;
						if ($imgnum == 1)
							$image_attributes = array('image', 'small_image', 'thumbnail');
						$product->addImageToMediaGallery($image, $image_attributes, false, false);
						$output .= "$sku added ".basename($image)." to ".$product->getName()."\n";
					foreach($images as $image){
				} else {
					$output .= "******* ERROR: can't find product for ".$sku." ********** \n";
			} else {
				$output .= "******* ERROR: unable to locate image 1 for ".$sku." ********** \n";

		if ($output != ""){
			echo $ouput;
			//or you can email this somewhere


Leave a Reply

Your email address will not be published. Required fields are marked *