DIGITAL4FRONT / CODE BASE

Secure PHP PDO Image Uploads, Updates, Deletes and File Cleanup

Learn how to securely upload, replace and delete product images using PHP and PDO. Includes file validation, safe filenames, database transactions, orphaned-file prevention, CSRF protection and practical code examples for PHP applications.

Share

PHP and PDO can manage product images securely by storing generated filenames in MySQL while keeping the actual files on disk. The important part is coordinating file uploads, database updates and file deletion correctly. A database transaction cannot roll back a filesystem operation, so the application must handle failures explicitly and clean up files that are no longer referenced.

This guide demonstrates a practical approach for native PHP applications, including product management systems, CRM platforms and custom eCommerce websites.

Why basic PHP image uploads are risky

A common implementation looks like this:

php
<?php
$filename = $_FILES['image']['name'];
move_uploaded_file(
    $_FILES['image']['tmp_name'],
    'uploads/' . $filename
);

Although this can work, it introduces several problems.

The original filename is controlled by the person uploading the file. Two uploads with the same name can overwrite each other. A malicious user could submit a filename containing unexpected path characters or upload a file that is not actually an image.

There is also no file-size restriction, no content validation and no protection against executable files being placed in a publicly accessible directory.

A better implementation validates the uploaded content, generates a new filename and stores files in a controlled location.

1. Create a suitable database structure

For a simple product-management application, the products table can store a reference to one image per product.

sql
CREATE TABLE products (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(150) NOT NULL,
    image_file VARCHAR(64) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

The image_file column stores only the generated filename, not the complete filesystem path.

For example, an image might be stored as:

text
9f27a61c8b4d0e35f719a26b0d8c4e51.webp

The application determines the storage directory. Users cannot select arbitrary filesystem paths.

This example assumes each image belongs to one product. Applications supporting shared images should use a separate media table with explicit relationships.

2. Store uploads outside the public web directory

A safer directory structure separates public application files from uploaded content.

text
application/
    public/
        index.php
        admin/
            products.php
            product-images.php
    private/
        uploads/
            products/
    config/
    vendor/

Configure your web server so that only the public directory is accessible through HTTP.

The private uploads directory must not be directly accessible from the browser.

Configure the following environment variables:

bash
DB_DSN=mysql:host=localhost;dbname=webshop;charset=utf8mb4
DB_USER=webshop_user
DB_PASS=your_database_password
APP_IMAGE_DIR=/absolute/path/to/application/private/uploads/products

These are example settings. Supply real values through your hosting configuration or a protected environment file. Never commit production passwords to source control.

The upload directory must exist and be writable by the PHP process.

3. Securely validate uploaded images

Do not trust the filename extension or the MIME type submitted by the browser.

Use PHP's Fileinfo extension to inspect the uploaded file and verify its image structure before accepting it.

The following function supports JPEG, PNG and WebP images.

php
<?php
declare(strict_types=1);

function validateProductImage(array $upload): string
{
    if (($upload['error'] ?? null) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Image upload failed.');
    }

    $tmp = $upload['tmp_name'] ?? null;
    $size = $upload['size'] ?? null;

    if (!is_string($tmp) || !is_uploaded_file($tmp)) {
        throw new RuntimeException('Invalid uploaded file.');
    }

    if (!is_int($size) || $size < 1 || $size > 5 * 1024 * 1024) {
        throw new RuntimeException('Image exceeds the 5 MB limit.');
    }

    $allowed = [
        'image/jpeg' => ['extension' => 'jpg', 'type' => IMAGETYPE_JPEG],
        'image/png'  => ['extension' => 'png', 'type' => IMAGETYPE_PNG],
        'image/webp' => ['extension' => 'webp', 'type' => IMAGETYPE_WEBP],
    ];

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmp);

    if (!is_string($mime) || !isset($allowed[$mime])) {
        throw new RuntimeException('Unsupported image format.');
    }

    $details = @getimagesize($tmp);

    if ($details === false ||
        ($details[2] ?? null) !== $allowed[$mime]['type']) {
        throw new RuntimeException('Invalid image content.');
    }

    $width = (int) $details[0];
    $height = (int) $details[1];

    if ($width < 1 || $height < 1 ||
        $width * $height > 16000000) {
        throw new RuntimeException('Invalid image dimensions.');
    }

    return $allowed[$mime]['extension'];
}

This function checks upload status, file size, actual MIME type, recognised image format and dimensions.

These checks reduce common risks but do not guarantee that every accepted file is harmless. For stronger protection, decode and re-encode supported images with a maintained image-processing library, and enforce server-side execution restrictions.

SVG uploads are deliberately excluded because SVG files can contain active content and require additional sanitisation.

4. Generate safe filenames

Never use the original filename as the stored filename.

Generate a cryptographically random name and append the extension established during validation.

php
<?php
function generateImageFilename(string $extension): string
{
    return bin2hex(random_bytes(16)) . '.' . $extension;
}

This produces an unpredictable filename with 128 bits of randomness.

The application should store the filename in the database and construct filesystem paths internally.

Do not allow filename values from hidden form fields or query parameters to determine which files are deleted.

5. Complete product image upload and update handler

The following example combines secure uploading with PDO database updates.

It assumes that the database table already exists and that your application has implemented administrator authentication and session-based CSRF tokens.

Save the previous two functions in a PHP file named image-functions.php and require that file from the handler below.

The handler supports creating a product, changing its name, replacing its image, removing an image and deleting a product.

Save this example as public/admin/product-images.php.

php
<?php
declare(strict_types=1);

session_start();
require_once __DIR__ . '/../../config/image-functions.php';

if (empty($_SESSION['user_id']) ||
    ($_SESSION['role'] ?? '') !== 'admin') {
    http_response_code(403);
    exit('Access denied.');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method not allowed.');
}

$storedToken = $_SESSION['csrf_token'] ?? null;
$submittedToken = $_POST['csrf_token'] ?? null;

if (!is_string($storedToken) ||
    !is_string($submittedToken) ||
    !hash_equals($storedToken, $submittedToken)) {
    http_response_code(403);
    exit('Invalid CSRF token.');
}

$action = $_POST['action'] ?? '';

if (!in_array($action, ['create', 'update', 'remove', 'delete'], true)) {
    http_response_code(400);
    exit('Invalid action.');
}

$id = null;

if ($action !== 'create') {
    $id = filter_var(
        $_POST['id'] ?? null,
        FILTER_VALIDATE_INT,
        ['options' => ['min_range' => 1]]
    );

    if ($id === false || $id === null) {
        http_response_code(400);
        exit('Invalid product ID.');
    }
}

$name = '';

if ($action === 'create' || $action === 'update') {
    $submittedName = $_POST['name'] ?? null;

    if (!is_string($submittedName)) {
        http_response_code(400);
        exit('Invalid product name.');
    }

    $name = trim($submittedName);

    if ($name === '' || strlen($name) > 150) {
        http_response_code(400);
        exit('Invalid product name.');
    }
}

$directory = getenv('APP_IMAGE_DIR');

if (!$directory || !is_dir($directory) || !is_writable($directory)) {
    throw new RuntimeException('Image storage is not configured.');
}

$pdo = new PDO(
    getenv('DB_DSN'),
    getenv('DB_USER'),
    getenv('DB_PASS'),
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
);

$newFilename = null;
$oldFilename = null;
$shouldCleanupOld = false;

try {
    if (($action === 'create' || $action === 'update') &&
        isset($_FILES['image'])) {

        $upload = $_FILES['image'];

        if (!is_array($upload)) {
            throw new RuntimeException('Invalid upload request.');
        }

        if (($upload['error'] ?? null) !== UPLOAD_ERR_NO_FILE) {
            $extension = validateProductImage($upload);
            $newFilename = generateImageFilename($extension);
            $destination = $directory . DIRECTORY_SEPARATOR . $newFilename;

            if (!move_uploaded_file($upload['tmp_name'], $destination)) {
                throw new RuntimeException('Unable to save image.');
            }
        }
    }

    $pdo->beginTransaction();

    if ($action !== 'create') {
        $stmt = $pdo->prepare(
            'SELECT image_file FROM products WHERE id = ? FOR UPDATE'
        );
        $stmt->execute([$id]);

        $oldFilename = $stmt->fetchColumn();

        if ($oldFilename === false) {
            throw new RuntimeException('Product not found.');
        }
    }

    if ($action === 'create') {
        $stmt = $pdo->prepare(
            'INSERT INTO products (name, image_file) VALUES (?, ?)'
        );
        $stmt->execute([$name, $newFilename]);

    } elseif ($action === 'update') {
        if ($newFilename !== null) {
            $stmt = $pdo->prepare(
                'UPDATE products SET name = ?, image_file = ? WHERE id = ?'
            );
            $stmt->execute([$name, $newFilename, $id]);
            $shouldCleanupOld = true;
        } else {
            $stmt = $pdo->prepare(
                'UPDATE products SET name = ? WHERE id = ?'
            );
            $stmt->execute([$name, $id]);
        }

    } elseif ($action === 'remove') {
        $stmt = $pdo->prepare(
            'UPDATE products SET image_file = NULL WHERE id = ?'
        );
        $stmt->execute([$id]);
        $shouldCleanupOld = true;

    } elseif ($action === 'delete') {
        $stmt = $pdo->prepare('DELETE FROM products WHERE id = ?');
        $stmt->execute([$id]);
        $shouldCleanupOld = true;
    }

    $pdo->commit();

} catch (Throwable $exception) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    if ($newFilename !== null) {
        $newPath = $directory . DIRECTORY_SEPARATOR . $newFilename;

        if (is_file($newPath)) {
            @unlink($newPath);
        }
    }

    error_log('Product image operation failed: ' . $exception->getMessage());
    http_response_code(500);
    exit('Unable to save product changes.');
}

// Remove the previous image only after a successful commit.
if ($shouldCleanupOld && is_string($oldFilename)) {
    try {
        $validFilename = preg_match(
            '/\A[a-f0-9]{32}\.(?:jpg|png|webp)\z/D',
            $oldFilename
        );

        if ($validFilename) {
            $check = $pdo->prepare(
                'SELECT COUNT(*) FROM products WHERE image_file = ?'
            );
            $check->execute([$oldFilename]);

            if ((int) $check->fetchColumn() === 0) {
                $oldPath = $directory . DIRECTORY_SEPARATOR . $oldFilename;

                if (is_file($oldPath) && !unlink($oldPath)) {
                    error_log('Old product image could not be removed.');
                }
            }
        }
    } catch (Throwable $exception) {
        error_log('Product image cleanup failed: ' . $exception->getMessage());
    }
}

header('Location: /admin/products.php', true, 303);
exit;

This example deliberately separates database changes from filesystem cleanup.

It also uses SELECT FOR UPDATE to lock an existing product row during modification. This reduces race conditions when two administrators update the same product concurrently.

The application never trusts an existing image filename submitted through the browser. It retrieves the previous filename directly from the database.

For products referenced by orders or other tables, database foreign-key restrictions may prevent deletion. In those applications, archiving the product is often more appropriate than physically deleting its record.

6. Create the administrative upload form

The controller expects a POST request containing the action, product ID where applicable, product name, CSRF token and optional image.

The following example updates an existing product.

Place it inside an authenticated administrator page.

php
<?php
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<form method="post"
      action="/admin/product-images.php"
      enctype="multipart/form-data">

    <input type="hidden" name="action" value="update">
    <input type="hidden" name="id" value="<?= (int) $product['id'] ?>">

    <input type="hidden"
           name="csrf_token"
           value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">

    <label for="name">Product name</label>
    <input type="text"
           id="name"
           name="name"
           maxlength="150"
           value="<?= htmlspecialchars($product['name'], ENT_QUOTES, 'UTF-8') ?>"
           required>

    <label for="image">Replace product image</label>
    <input type="file"
           id="image"
           name="image"
           accept="image/jpeg,image/png,image/webp">

    <button type="submit">Save product</button>
</form>

The accept attribute improves the browser experience but is not a security control. All uploaded files must still pass server-side validation.

To create a product, change the action to create and omit the product ID. To remove an image or delete a product, submit the corresponding action and product ID through a POST form with a valid CSRF token.

Do not use ordinary GET links for destructive operations.

7. Display product images securely

Because the uploaded files are stored outside the public web directory, they cannot be linked directly using an ordinary uploads URL.

Instead, create a controlled PHP endpoint that retrieves the image reference from the database and streams the file to the browser.

The endpoint must validate the product ID and stored filename. It must never accept an arbitrary filesystem path from a request.

For example, a public product image URL could look like this:

text
https://example.com/product-image.php?id=125

The image-serving controller should retrieve image_file for product 125, validate that it matches the application's filename format and read the corresponding file from APP_IMAGE_DIR.

Set the appropriate Content-Type header and include:

php
<?php
header('X-Content-Type-Options: nosniff');

If the images belong to private CRM records or restricted products, check the current user's permissions before returning the file.

For public product images, consider response caching and a suitable image optimisation process.

8. Why PDO transactions cannot roll back uploaded files

This is one of the most important limitations to understand.

A PDO transaction controls database operations. It does not control the filesystem.

Consider this sequence:

1. PHP receives and validates an image.
2. The image is moved into private storage.
3. A database transaction begins.
4. The product record is updated.
5. The database commits.
6. The previous image is removed.

If the database update fails, the transaction can roll back and the application can attempt to remove the newly uploaded file.

If the database commits but deleting the old image fails, the new image reference remains correct. The old file becomes an orphan that can be removed later.

This ordering is generally preferable to deleting the previous image before confirming that the database has accepted the replacement.

However, it is not completely atomic. A server crash between saving the new file and committing the database transaction can still leave an orphaned file. A crash after a successful commit but before cleanup can leave the previous image behind.

For systems requiring stronger guarantees, use an upload-state table, durable cleanup jobs or an outbox-based process to coordinate retries and reconciliation.

9. Detect and remove orphaned image files

Even with careful exception handling, orphaned files can accumulate after process crashes, interrupted deployments or failed cleanup operations.

An orphaned image is a file that exists in storage but is no longer referenced by any product record.

A scheduled cleanup process can identify these files.

A safe cleanup routine should:

1. Run through the command line or a protected background worker.
2. Inspect only the configured product-image directory.
3. Process only filenames matching the application's generated format.
4. Compare each filename against the database.
5. Ignore recently created files that may still be involved in an active upload.
6. Log proposed deletions before enabling automatic removal.
7. Delete files only after confirming that no database record references them.

For example, the database lookup can use:

php
<?php
$stmt = $pdo->prepare(
    'SELECT COUNT(*) FROM products WHERE image_file = ?'
);

$stmt->execute([$filename]);

$isReferenced = (int) $stmt->fetchColumn() > 0;

If the result is false and the file is older than an appropriate grace period, it becomes a candidate for cleanup.

A grace period of 24 to 48 hours may be suitable for a small application, provided uploads cannot legitimately remain pending for that long. Larger systems should base the threshold on their actual workflow.

Use a dry-run mode first. Log the files that would be deleted without actually deleting them.

If your application supports multiple products referencing the same image, include all relevant tables and relationships in the reference check.

10. Additional security considerations

File upload validation is only one part of application security.

Administrative image operations must require authentication and server-side authorisation. CSRF protection should be applied to every state-changing form.

Store uploaded files outside the public web root wherever practical. If files must be publicly accessible, configure the web server to prevent script execution in upload directories.

Do not assume that changing an uploaded PHP file's extension makes the underlying content harmless.

Use generated filenames, restrict permissions, limit upload sizes and avoid directly exposing internal filesystem paths in error messages.

For image-processing workloads, consider decoding and re-encoding images to remove unwanted metadata and reject malformed content. Apply memory and pixel-count limits to avoid excessively expensive image processing.

Do not use JavaScript or HTML file validation as a replacement for server-side checks.

The OWASP File Upload Cheat Sheet provides additional security guidance.

11. Testing the implementation

Before deploying, test the complete image lifecycle.

Create a product with a valid image and confirm that the database stores the generated filename.

Update the product without selecting another image. The existing image must remain unchanged.

Replace the image and confirm that the database references the new file. The previous file should be removed only after the database transaction commits.

Submit an invalid image type, an oversized file and an intentionally malformed upload. Each should be rejected without modifying the existing product.

Simulate a database failure after saving a new image and confirm that the temporary new file is removed where possible.

Remove an image without deleting the product. The database reference should become NULL and the old file should be cleaned up.

Finally, test concurrent updates, missing products, invalid CSRF tokens and unauthorised requests.

Final recommendations

The safest practical approach for small PHP applications is to store images separately from the database, use generated filenames, validate uploaded content and keep database changes inside transactions.

Never delete an existing image before confirming that its replacement has been saved successfully.

Remember that database transactions cannot provide complete atomicity across MySQL and the filesystem. Use compensating cleanup operations and periodic orphan-file reconciliation.

For larger eCommerce or CRM platforms, consider a dedicated media-management component with background processing, image variants, storage auditing and lifecycle management.

The same principles apply to profile pictures, product images, document attachments and other user-uploaded files.

For additional implementation details, consult the PHP file upload documentation, PDO transaction documentation and PHP move_uploaded_file reference.

WhatsApp us