PHPackages                             anomanderrevan/sanitizr - 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. anomanderrevan/sanitizr

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

anomanderrevan/sanitizr
=======================

A centralized, customizable security &amp; input sanitization package for laravel

00PHP

Since Mar 12Pushed 1y ago1 watchersCompare

[ Source](https://github.com/AnomanderRevan/sanitizr)[ Packagist](https://packagist.org/packages/anomanderrevan/sanitizr)[ RSS](/packages/anomanderrevan-sanitizr/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (2)Used By (0)

Sanitizr
========

[](#sanitizr)

A Laravel Security &amp; Input Sanitization Package

Sanitizr is a Laravel package designed to sanitize user input, ensuring your application is protected against common security threats like SQL injection, XSS, and command injection.

---

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

[](#installation)

To install the `sanitizr` package, use Composer:

```
composer require anomanderrevan/sanitizr
```

---

Publishing the Configuration File
---------------------------------

[](#publishing-the-configuration-file)

After installing the package, publish the configuration file to customize the sanitization rules and filters:

```
php artisan vendor:publish --tag=sanitizr-config
```

This will create a `sanitizr.php` file in the `config` directory of your Laravel application.

---

Publish the Middleware
----------------------

[](#publish-the-middleware)

You can access the middleware from the package directly, or you can publish it to the app should you wish to customise it. If you wish to publish the middleware, you can do so with the following command:

```
php artisan vendor:publish --tag=sanitizr-middleware
```

If you are publishing the middleware, you will need to update the namespace in the `app/Http/Middleware/AutoSan.php` file to match your app's namespace.

```
namespace App\Http\Middleware;
//namespace AnomanderRevan\Sanitizr\Http\Middleware;
```

---

Configuration
-------------

[](#configuration)

The `sanitizr.php` configuration file allows you to define rules and filters for sanitizing input. Below is an overview of the configuration options:

### 1. **Rules**

[](#1-rules)

Rules group filters that can be applied to entire requests. For example:

```
    //Define the rules that will be used to sanitize the data
    'rules' => [
        //Rules applied to entire $request
        'global' => [
            'api' => ['escape_html'],
            'form' => [ 'strip_tags'],
            'security' => [ 'xss_check', 'sql_check' ],
        ],
        //Rules applied to specific fields
        'field' => [
            'first_name' => ['lowercase', 'ucfirst'],
            'last_name' => ['lowercase', 'ucfirst'],
            'email' => ['lowercase', 'sanitize_email'],
            'eircode' => ['uppercase', 'remove_special_chars'],
            'phone' => ['phone_plus_replace', 'remove_special_chars', 'numeric'],
            'mobile' => ['phone_plus_replace', 'remove_special_chars', 'numeric'],
        ],
    ],
```

- **`global`**: Global rules allow you to apply filters to each field.
- **`field`**: Field-specific rules allow you to apply filters to individual fields by name.

*Note: Global filters are applied first, and then field-specific filters are applied.*

### 2. **Excluded Fields**

[](#2-excluded-fields)

Excluded Fields allows you to ensure specific fields are exempt from sanitization. For example:

```
'excluded_fields' => [
        'csrf_token',
        'username',
        'password',
        'password_confirmation',
    ],
```

### 3. **Filters**

[](#3-filters)

Filters are reusable functions for sanitizing data. You can use pre-defined filters within the array or add custom filters to suit your app. For example:

```
'filters' => [
    'escape_html' => function($value) { return htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); },
    'strip_tags' => function($value) { return strip_tags($value); },
    'phone_plus_replace' => function($value) { return preg_replace('/\+/', '00', $value); },
],
```

---

Usage
-----

[](#usage)

### Applying Rules to Requests

[](#applying-rules-to-requests)

To apply sanitization rules to incoming requests, use the `AutoSan` middleware. To apply it to all routes, you can add it to your `app/Http/Kernel.php` file.

If you are using the middleware from the package directly:

```
protected $middlewareGroups = [
    // For web routes
    'web' => [
        // Other middleware
        \AnomanderRevan\Sanitizr\Http\Middleware\AutoSan::class,
    ],
    // For API routes
    'api' => [
        // Other middleware
        \AnomanderRevan\Sanitizr\Http\Middleware\AutoSan::class,
    ],
];
```

If you are publishing the middleware:

```
protected $middlewareGroups = [
    // For web routes
    'web' => [
        // Other middleware
        \App\Http\Middleware\AutoSan::class,
    ],
    // For API routes
    'api' => [
        // Other middleware
        \App\Http\Middleware\AutoSan::class,
    ],
];
```

Alternatively you may wish to apply the middleware to specific routes. You can do this by adding the middleware to the route definition in your `routes/web.php` or `routes/api.php` file:

```
Route::post('/test-normal', [TestController::class, 'testPost']);
Route::post('/test-security-rule', [TestController::class, 'testPost'])->middleware(AutoSan::class . ':security');
Route::post('/test-api-rule', [TestController::class, 'testPost'])->middleware(AutoSan::class . ':api');
```

---

Security Features
-----------------

[](#security-features)

Sanitizr includes built-in filters which can be applied to detect and mitigate common security threats. By default these are grouped under the `security` rule, but you can also apply them to specific fields if needed.

1. **SQL Injection**: The `sql_check` filter detects and blocks SQL injection patterns.
2. **XSS**: The `xss_check` filter identifies and quarantines malicious `` tags.
3. **Command Injection**: The `cmd_check` filter prevents command injection attempts.

When a potential security threat is detected, the middleware will log the incident and return a 400 response before the request is processed by the application.

You can also specify whether to automatically check for injection on URLs by enabling the `run_check_on_url` in the config. You can enable this feature in the configuration file:

```
    'run_check_on_url' => true,
```

---

Logging
-------

[](#logging)

When a potential security threat is detected, Sanitizr logs the incident using Laravel's `Log` facade. You can review the logs in the `storage/logs/laravel.log` file.

---

Testing
-------

[](#testing)

The package comes with a set of unit tests to ensure the sanitization functionality works as expected. To test the sanitization functionality locally, you can write unit tests for your application. For example:

```
public function testSanitization()
{
    $input = [
        'first_name' => 'jOhN',
        'email' => 'EXAMPLE@EXAMPLE.COM',
    ];

    $sanitized = app('sanitizr')->sanitize($input, 'security');

    $this->assertEquals('John', $sanitized['first_name']);
    $this->assertEquals('example@example.com', $sanitized['email']);
}
```

You can run the tests using PHPUnit:

```
php artisan test
```

---

Support
-------

[](#support)

If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/anomanderrevan/sanitizr).

---

License
-------

[](#license)

This package is open-source software licensed under the [MIT license](LICENSE).

```

```

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity0

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity17

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/53d806d8925a67eef307e011217700c08600deeaa53a4eb1cbcf727e918023fb?d=identicon)[AnomanderRevan](/maintainers/AnomanderRevan)

---

Top Contributors

[![AnomanderRevan](https://avatars.githubusercontent.com/u/49555563?v=4)](https://github.com/AnomanderRevan "AnomanderRevan (31 commits)")

### Embed Badge

![Health badge](/badges/anomanderrevan-sanitizr/health.svg)

```
[![Health](https://phpackages.com/badges/anomanderrevan-sanitizr/health.svg)](https://phpackages.com/packages/anomanderrevan-sanitizr)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[nette/forms

📝 Nette Forms: generating, validating and processing secure forms in PHP. Handy API, fully customizable, server &amp; client side validation and mature design.

54013.2M446](/packages/nette-forms)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
