Post by serpro-ltd » Sat Aug 17, 2024 2:27 pm

When we migrated our Xcart sytem over to Opencart it moved all the images contained in the old system.

The way Xcart uses images is a bit clumsy in that it won't reuse an existing image it will create a copy of it which means that there is a lot of "bloat" in the image file system.

So needed to remove the unused images to reduce the number of files on the new system.

Didn't want to straight forward delete the file "just in case" as it where, so decided to "move" the images to a safe place.

Looked in the market place and again some very nice pieces of work there but for yet more money to do a simple task. So put my old brain to work and come up with a script that will move unused images to a safe directory for re-use or backup or deletion. up to you. It also has a checkbox on each file so you can choose which files to move. done this as there are some "system" files for things like Journal3 images that should not be removed. I don't know if it is safe to delete or not and can't be bothered to find out, so thought it best just to leave them. Again, your choice.

When I used it I'm pretty sure that I had to manually create a sub-dir under images called "unused" and one under that called "catalog". I seem to recall that on my system it wouldn't create the unused dir on the hoof. Don't know why, maybe someone else can figure that one out.

If you change to code for the better please place it here for other users to benefit from. I make no apologies for the coding, I'm 70 years old and am not into people saying I should have done this or that. Change it if you wish, up to you.

Obviously, make backups of all your site before using mods and scripts. You may have to change directory names.

Regards
Adrian

Code: Select all

<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection details
$host = 'xxxxxxxxxx.data';
$db = 'xxxxxxxxx';
$user = 'xxxxxxxxx';
$pass = '?????????????';

// Create connection using PDO
try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Function to scan the image directory
function scanImageDirectory($dir)
{
    $allImages = [];
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($files as $file) {
        if ($file->isFile()) {
            $relativePath = str_replace('\\', '/', substr($file->getPathname(), strlen($dir) + 1));
            $allImages[] = 'catalog/' . $relativePath;
        }
    }
    return $allImages;
}

// Move selected images to the 'unused' directory
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['images'])) {
    $selectedImages = $_POST['images'];
    $unusedDir = 'image/unused/catalog';

    foreach ($selectedImages as $image) {
        $source = 'image/' . $image;
        $destination = $unusedDir . '/' . $image;

        // Ensure the destination directory exists
        $destinationDir = dirname($destination);
        if (!is_dir($destinationDir)) {
            if (!mkdir($destinationDir, 0777, true)) {
                echo "<p>Failed to create directory: $destinationDir</p>";
                continue; // Skip this file if directory creation fails
            }
        }

        // Move the file
        if (file_exists($source)) {
            if (!rename($source, $destination)) {
                echo "<p>Failed to move file: $source to $destination</p>";
            } else {
                echo "<p>Moved $source to $destination</p>";
            }
        } else {
            echo "<p>File not found: $source</p>";
        }
    }
}

// Get all images used in products, categories, and other entities
$usedImages = [];

$query = "SELECT image FROM oc_product WHERE image IS NOT NULL
          UNION
          SELECT image FROM oc_category WHERE image IS NOT NULL
          UNION
          SELECT image FROM oc_banner_image WHERE image IS NOT NULL
          UNION
          SELECT image FROM oc_product_image WHERE image IS NOT NULL";

$stmt = $pdo->query($query);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $usedImages[] = $row['image'];
}

// Scan the image directory
$imageDir = 'image/catalog';
$allImages = scanImageDirectory($imageDir);

// Identify unused images
$unusedImages = array_diff($allImages, $usedImages);

// Output unused images
if (!empty($unusedImages)) {
    echo "<h2>Unused Images</h2>";
    echo "<form method='post'><ul>";
    foreach ($unusedImages as $unusedImage) {
        echo "<li><input type='checkbox' name='images[]' value='$unusedImage'> $unusedImage</li>";
    }
    echo "</ul><input type='submit' value='Move Selected to Unused'></form>";
} else {
    echo "<p>No unused images found!</p>";
}

Serpro Spill Management
www.serpro.co.uk

Opencart 3.0.03.9
Journal3
Order Number Manager
PDF Invoice Pro
Category Description By Multi Store
MASS products update: Stores
MultiStore Payment Methods
Price Update With Option Change
Product Description By Multi Store
Quick Admin Search By Mart Extensions
Ultimate Shipping


User avatar
Newbie

Posts

Joined
Wed Aug 07, 2024 2:07 am
Location - Maidstone Uk

User avatar
Guru Member

Posts

Joined
Wed Dec 05, 2007 3:38 am

Who is online

Users browsing this forum: No registered users and 8 guests