Remove a Specific Image from all Cache Directories

I’ve had instances where I’ve updated a specific image yet wanted to keep the same image name etc. If you upload the image via the admin panel, it will append a “_1” to the file name thereby creating a whole new image.

The code below will delete the specific image (or images) from every cache directory, thereby forcing Magento to refresh the cached image with the updated one that you placed in the main image directory. Right now, as a precaution it’s limited to deleting a max of six versions at a time (you can remove/change this is you like) and it’s accepting only a specific jpg file (this can also be removed and it will delete any files that match the pattern entered.)


<!DOCTYPE html>
<head>
<title>Remove a Specific Image from Cache</title>
</head>

<?php

$path = $_SERVER["DOCUMENT_ROOT"]. "/media/catalog/product/cache/";

if (!empty($_GET["image"])) {
$image = $_GET["image"];
if (preg_match("/.jpg/i", $image)) {
$reply = rem_image($path,$image);
echo "<br>$reply";
} else {
echo "<br>Invalid Image Name: $image";
}
}
?>

<h2>Remove an Image from Cache Directories</h2>
<h3> (Max Occurances removed = 6 at a time) </h3>

<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter Image file (ie 1234.jpg): <input type="text" name="image" value="<?php echo $image;?>">
<br>
<input type="submit" name="submit" value="Submit">
</form>

<br><br>
<a href="<?php echo $_SERVER['PHP_SELF'] ?>">Clear and Start Over</a>

<?php

function rem_image($path,$match){
static $deld = 0, $dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if((is_file($file)) and ($deld < 6)){
$dsize += filesize($file);
unlink($file);
echo "<br>$file removed";
$deld++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
rem_image($path.$dir,$match);
}
}
return "$deld files deleted with a total size of $dsize bytes";
}

?>

Place this code in a protected directory and you’re good to go.

 

Leave a Reply