PHPackages                             timahfouz/svg-sanitizer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. timahfouz/svg-sanitizer

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

timahfouz/svg-sanitizer
=======================

A Laravel package for sanitizing SVG files and SVG code to prevent XSS attacks

v1.0.0(5mo ago)01MITPHPPHP ^8.1

Since Jan 16Pushed 5mo agoCompare

[ Source](https://github.com/timahfouz/svg-sanitizer)[ Packagist](https://packagist.org/packages/timahfouz/svg-sanitizer)[ RSS](/packages/timahfouz-svg-sanitizer/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (5)Versions (2)Used By (0)

Laravel SVG Sanitizer
=====================

[](#laravel-svg-sanitizer)

A comprehensive Laravel package for sanitizing SVG files and SVG code to prevent XSS (Cross-Site Scripting) attacks.

[![Latest Version on Packagist](https://camo.githubusercontent.com/f62a68178a15f13d28f6b7da28926c994cc7c91c923066a891da568bfa64ec2a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f796f75722d76656e646f722f6c61726176656c2d7376672d73616e6974697a65722e737667)](https://packagist.org/packages/your-vendor/laravel-svg-sanitizer)[![License](https://camo.githubusercontent.com/261e81d292951909756803e389295a4f332acadc1f5409fd791d11caea88c5d6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f796f75722d76656e646f722f6c61726176656c2d7376672d73616e6974697a65722e737667)](https://packagist.org/packages/your-vendor/laravel-svg-sanitizer)

Features
--------

[](#features)

- ✅ **SVG File Validation** - Validate uploaded SVG files for malicious content
- ✅ **SVG Code Validation** - Validate SVG code from text inputs/textareas
- ✅ **SVG File Sanitization** - Clean uploaded SVG files before storing
- ✅ **SVG Code Sanitization** - Clean SVG code strings before saving to database
- ✅ **Configurable** - Customize allowed tags, attributes, and dangerous patterns
- ✅ **Middleware** - Add security headers when serving SVG files
- ✅ **Laravel 10 &amp; 11 Support**

Installation
------------

[](#installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require timahfouz/svg-sanitizer
```

### Step 2: Publish Configuration (Optional)

[](#step-2-publish-configuration-optional)

```
php artisan vendor:publish --tag=svg-sanitizer-config
```

This will create `config/svg-sanitizer.php` where you can customize:

- Allowed SVG tags
- Allowed SVG attributes
- Dangerous patterns to detect
- Max file size and code length

### Step 3: Register Middleware (Optional)

[](#step-3-register-middleware-optional)

Add to `bootstrap/app.php` (Laravel 11):

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'svg.headers' => \Timahfouz\SvgSanitizer\Middleware\SecureSvgHeaders::class,
    ]);
})
```

Or in `app/Http/Kernel.php` (Laravel 10):

```
protected $middlewareAliases = [
    // ...
    'svg.headers' => \Timahfouz\SvgSanitizer\Middleware\SecureSvgHeaders::class,
];
```

Usage
-----

[](#usage)

### Validation Rules

[](#validation-rules)

#### For SVG File Uploads

[](#for-svg-file-uploads)

Use `svg_file_safe` rule or the `SvgFileSafe` class:

```
use Timahfouz\SvgSanitizer\Rules\SvgFileSafe;

// Using string rule
$request->validate([
    'icon' => 'required|file|mimes:svg|svg_file_safe',
]);

// Using rule class
$request->validate([
    'icon' => ['required', 'file', 'mimes:svg', new SvgFileSafe()],
]);
```

#### For SVG Code (Textarea Input)

[](#for-svg-code-textarea-input)

Use `svg_code_safe` rule or the `SvgCodeSafe` class:

```
use Timahfouz\SvgSanitizer\Rules\SvgCodeSafe;

// Using string rule
$request->validate([
    'icon' => 'nullable|string|max:10000|svg_code_safe',
]);

// Using rule class
$request->validate([
    'icon' => ['nullable', 'string', 'max:10000', new SvgCodeSafe()],
]);
```

### Sanitization

[](#sanitization)

#### Using the Facade

[](#using-the-facade)

```
use Timahfouz\SvgSanitizer\Facades\SvgSanitizer;

// Sanitize an uploaded file
$cleanSvg = SvgSanitizer::sanitizeFile($request->file('icon'));

// Sanitize SVG code from textarea
$cleanSvg = SvgSanitizer::sanitizeCode($request->input('icon'));

// Check if file is safe (without sanitizing)
if (SvgSanitizer::isFileSafe($request->file('icon'))) {
    // File is safe
}

// Check if code is safe (without sanitizing)
if (SvgSanitizer::isCodeSafe($request->input('icon'))) {
    // Code is safe
}
```

#### Using Dependency Injection

[](#using-dependency-injection)

```
use Timahfouz\SvgSanitizer\Services\SvgFileSanitizer;
use Timahfouz\SvgSanitizer\Services\SvgCodeSanitizer;

class MyController extends Controller
{
    public function __construct(
        protected SvgFileSanitizer $fileSanitizer,
        protected SvgCodeSanitizer $codeSanitizer
    ) {}

    public function store(Request $request)
    {
        // Sanitize file upload
        if ($request->hasFile('icon')) {
            $cleanSvg = $this->fileSanitizer->sanitize($request->file('icon'));

            if ($cleanSvg === null) {
                return back()->withErrors(['icon' => 'Invalid or unsafe SVG file.']);
            }

            // Store the sanitized SVG
            Storage::put('icons/icon.svg', $cleanSvg);
        }

        // Sanitize code input
        $iconCode = $this->codeSanitizer->sanitize($request->input('icon'));

        if ($iconCode === null && $request->filled('icon')) {
            return back()->withErrors(['icon' => 'Invalid or unsafe SVG code.']);
        }

        // Save to database
        Category::create([
            'name' => $request->input('name'),
            'icon' => $iconCode,
        ]);
    }
}
```

### Complete Controller Example

[](#complete-controller-example)

```
