Open source documentation

Laravel Image Sanitize

Prevent malicious code execution through uploaded image files by detecting suspicious payload patterns and re-encoding unsafe images.

composer require laravel-at/laravel-image-sanitize

Laravel Image Sanitize package logo
Package
laravel-at/laravel-image-sanitize
Laravel
Laravel: ^12.0 | ^13.0
PHP
PHP: ^8.3
License
License: MIT
Repository
GitHub
Packagist
Package registry

Maintained: supports Laravel 12–13 and PHP 8.3+.

MIT licensed · defense-in-depth middleware · raster images

Security pipeline

A narrow layer in a complete upload flow

The package does one job deliberately. The surrounding application remains responsible for validation, authorization, and safe storage.

  1. 01 Install Add the middleware to the application.
  2. 02 Inspect Check supported uploads for suspicious markers.
  3. 03 Re-encode Rewrite suspicious images through Intervention Image.
  4. 04 Continue safely Keep validation, authorization, and storage controls.

Introduction

Laravel Image Sanitize is a small Laravel middleware for image upload flows. It scans uploaded image files for suspicious payload markers such as PHP code or PHAR references, and when detected, re-encodes the image through Intervention Image to strip embedded payload content.

The package is intentionally narrow: detect suspicious image uploads, rewrite unsafe image contents, and keep the surrounding Laravel validation and storage decisions in your application.

For the package maintenance story behind the current release, read Modernizing a Laravel Security Package for Intervention Image 4.

How does Laravel Image Sanitize help with image upload security?

Laravel Image Sanitize adds a defense-in-depth layer to Laravel image upload flows by detecting suspicious PHP or PHAR payload markers inside uploaded image files and re-encoding unsafe images through Intervention Image before the controller continues.

It does not replace Laravel validation, MIME checks, authorization, antivirus scanning, or safe storage outside executable paths. Use it when uploaded images pass through avatars, CMS media libraries, marketplaces, admin panels, or any flow where image contents should be normalized before storage.

SVG files are intentionally excluded by default because SVG can contain active content and needs a different security model than raster image re-encoding.

How do I sanitize uploaded images in Laravel?

Strip EXIF metadata, re-encode the image through GD or Imagick, and reject disguised payloads before storage. Laravel Image Sanitize handles this as middleware, without custom re-encoding logic in every upload route.

What upload vulnerabilities does image sanitization prevent?

It helps prevent polyglot files, embedded PHP or JavaScript payloads, SVG-based XSS, and metadata-based exploits. Sanitization re-renders the image binary so embedded code does not survive upload handling.

Installation

Install the package with Composer:

bash
composer require laravel-at/laravel-image-sanitize

Basic Usage

Attach the middleware directly to upload routes that accept image files.

php
use App\Http\Controllers\FileController;
use LaravelAt\ImageSanitize\ImageSanitizeMiddleware;

Route::post('/files', [FileController::class, 'upload'])
    ->name('file.upload')
    ->middleware(ImageSanitizeMiddleware::class);

How do you add Laravel Image Sanitize to an upload flow?

Use Composer to install Laravel Image Sanitize, attach the middleware to image upload routes, publish the config when defaults need changing, and keep Laravel validation, authorization, MIME checks, safe storage, and monitoring around the package.

A typical rollout is small: install the Composer package, register the middleware class or alias, and apply it only to routes that receive raster images. The published config controls allowed MIME types, detection patterns, image driver, output quality, auto-orientation, animation decoding, and metadata stripping.

For implementation details, use the installation, middleware alias, and configuration examples below. For release history and package-level changes, see the GitHub releases.

Middleware Alias

In Laravel 12 and 13, you can register a readable middleware alias in bootstrap/app.php.

php
use Illuminate\Foundation\Configuration\Middleware;
use LaravelAt\ImageSanitize\ImageSanitizeMiddleware;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'image-sanitize' => ImageSanitizeMiddleware::class,
    ]);
})

Then use the alias on your route:

php
Route::post('/files', [FileController::class, 'upload'])
    ->name('file.upload')
    ->middleware('image-sanitize');

Configuration

Publish the configuration file when you need to adjust allowed MIME types, detection patterns, image driver, quality, orientation handling, animation decoding, or metadata stripping.

bash
php artisan vendor:publish --tag=image-sanitize-config

The default configuration is deliberately compact:

php
return [
    'allowed_mime_types' => [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp',
        'image/webp',
    ],

    'patterns' => [
        '<?php',
        'phar',
    ],

    'driver' => \Intervention\Image\Drivers\Gd\Driver::class,
    'quality' => 100,
    'auto_orientation' => true,
    'decode_animation' => true,
    'strip_metadata' => true,
];

Direct Usage

You can call the sanitizer directly when you are handling image bytes outside the middleware flow.

php
if (ImageSanitize::detect($contents)) {
    $contents = (string) ImageSanitize::sanitize($contents);
}

How It Works

  1. 1 The middleware inspects uploaded image files that match the configured MIME type allow-list.
  2. 2 File contents are scanned for configured suspicious payload markers such as PHP open tags and PHAR references.
  3. 3 When a suspicious marker is detected, the image is decoded and re-encoded with Intervention Image.
  4. 4 The rewritten image content replaces the original upload content before your controller continues.

Security Notes

  • This package is defense-in-depth for image upload flows.
  • It should complement Laravel validation, MIME checks, storage outside public execution paths, and normal upload security practices.
  • SVG is intentionally not supported by default.
  • The package rewrites detected images by decoding and re-encoding them with Intervention Image.

If you need broader help around secure Laravel upload flows, package design, or platform risk, see my Laravel development services and secure Laravel platform consulting.

Testing

Run the package test suite with Composer:

bash
composer test

Changelog

Release notes and version history live in the package repository. Check the GitHub releases for published changes, then use the modernization article for the package-level reasoning behind the current approach.

Credits