Create a Zip file of your active images

Here’s a straight-forward and fast way to backup all your images for active items into a zip file that can be downloaded or ftp’d to another site.

Another advantage of this methodology is it will also report on any “broken” images you may have (image doesn’t exist even though it’s defined in the product file)

1) You can change the $localname to include the document root path or just the path after the root etc.

2) This $localname can be included/excluded when adding the file to the zip (if you exclude it, you won’t have any┬ádirectory structure, only the files.


<?php
@set_time_limit (120); // seconds

$zip = new ZipArchive();

// Source directory to zip - include training slash
$directory = $_SERVER{'DOCUMENT_ROOT'} . "/media/catalog/product";
// Destination and file name of new zip file
$zipfile = "../var/export/product_images.zip";

if(file_exists($zipfile)) {unlink($zipfile); } // removes old zip first
if ($zip->open($zipfile, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$zipfile>\n");
}

// ENTER YOUR OWN DATABASE CONNECTION BELOW
require_once('CONFIG FILE');

$mydb = @mysql_connect($cfg['hostname_magento'], $cfg['username_magento'], $cfg['password_magento']) or die("Unable to connect to database<br><br>".mysql_error());
mysql_select_db($cfg['database_magento'], $mydb);
// ****************************************************************

$sql = "
SELECT DISTINCT value as 'image'
FROM catalog_product_entity_media_gallery
WHERE ((value <> '') and (value <> 'no_selection') )
LIMIT 9999
";

$result = mysql_query($sql);

while($row = mysql_fetch_assoc($result)) {

$total_processed++;

$filename = $directory . $row[image];

if(!file_exists($filename)) {
echo "<br>Missing Image: " . $row[image];
$total_missing++;
} else {
//$localname = substr($filename,strrpos($filename,'/') + 1); // removes entire path from file
$localname = str_replace($_SERVER{'DOCUMENT_ROOT'}, '', $filename); // removes just the document root from file
$zip->addFile($filename, $localname); // first parameter is path to the actual file, second is the path & filename that the file will have in the archive
//$zip->addFile($filename); // first parameter is path to the actual file, second is the path & filename that the file will have in the archive
}
}

echo "<br><br>Total Processed : $total_processed";
echo "<br>Total Missing : $total_missing";

echo "<br>$zipfile completed - status: " . $zip->status . "\n";

$zip->close();

?>

TIP: when you’re first testing, change the SQL LIMIT to something small (ie 25) so that you’re not creating a full backup until you’re satisfied with the results.

Leave a Reply