Увійти Реєстрація
Блог Серії
Кар'єра
Вакансії Компанії
Навчання
Документація Співбесіди Тестування Відео
Екосистема
Пакети Ресурси Проєкти Інструменти Події
Інше
Про нас Реклама

Laravel Image Sanitize

laravel-at/laravel-image-sanitize
v5.0.1 13 343 79.1k 20 серпня 2026
На GitHub

Компактний пакет для запобігання виконанню шкідливого коду в додатку через завантажені файли зображень.

10

Поділитись

README

Laravel Image Sanitize logo

Reduce the risk of malicious code execution!

Latest Version on Packagist GitHub Tests Action Status Total Downloads Laravel Compatibility

This is a small but handy package to reduce the risk of malicious code execution coming into your application through uploaded images. It was created after being inspired by @appelsiini's talk on How to Hack your Laravel Application

Installation

This version requires PHP 8.3+, Laravel 12 or 13, and Intervention Image 4.

You can install the package via composer:

composer require laravel-at/laravel-image-sanitize

Usage

Apply the middleware to routes that receive image uploads:

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

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

If you prefer a middleware alias, register it in your application's bootstrap/app.php file:

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 upload routes:

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

If you want to learn more about middlewares, please check out the official Laravel documentation.

Configuration

You may publish the configuration file:

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

The default configuration scans JPEG, PNG, GIF, BMP, and WebP uploads for suspicious byte patterns, then re-encodes matching images through Intervention Image. SVG files are not supported by default.

These defaults are a starting point. You may extend the patterns array with application-specific patterns while retaining the defaults. Contributions that benefit the broader community are welcome.

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,
];

You can also use the facade directly:

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

Pattern matching is case-insensitive, so <?php also detects variants such as <?PHP; you do not need to list each casing separately.

Published configuration files are not updated automatically. When upgrading, compare your application's patterns array with the package defaults.

Pattern scanning and image re-encoding are defense-in-depth measures. Applications should still validate file types and sizes, generate safe filenames, and store uploads in a location where they cannot be executed.

Testing

composer test

Run the full local quality check:

composer check

Or run the individual checks:

composer format-test
composer analyse
composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email adrian@nuernberger.me instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Коментарі

Увійдіть, щоб залишити коментар

Будьте першим, хто залишить коментар!

Схожі пакети

Image

intervention/image

Бібліотека для обробки зображень на PHP.

14,367 4.3.2 12

Laravel Excel

maatwebsite/excel

Імпорт та експорт Excel і CSV поверх PhpSpreadsheet: експорт з колекції чи запиту одним рядком, імпорт із валідацією і чергами для великих файлів. Найпоширеніше рішення для звітів і вивантажень.

12,704 4.0.1 13 3

Laravel Medialibrary

spatie/laravel-medialibrary

Пакет для асоціювання файлів з Eloquent-моделями. Надає зручний інтерфейс для управління медіа-файлами, пов'язаними з вашими моделями бази даних.

6,163 11.23.7 13 8

Browsershot

spatie/browsershot

Конвертуй веб-сторінку в зображення або PDF, використовуючи headless Chrome.

5,241 5.4.0 8

Image Optimizer

spatie/image-optimizer

Простий пакет для оптимізації зображень за допомогою PHP.

2,875 1.10.0 7

Fast Excel

rap2hpoutre/fast-excel

Швидкий імпорт та експорт Excel для Laravel.

2,322 v5.16.0 13 7