PHPackages                             shammaa/laravel-security - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. shammaa/laravel-security

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

shammaa/laravel-security
========================

Comprehensive security package for Laravel with protection against SQL Injection, XSS, CSRF, and all common vulnerabilities

v1.1.0(4mo ago)125MITPHPPHP ^8.1

Since Dec 22Pushed 4mo agoCompare

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

READMEChangelogDependencies (8)Versions (6)Used By (0)

Laravel Security Package
========================

[](#laravel-security-package)

Comprehensive security package for Laravel - Automatically protects against all types of security vulnerabilities!

⚡ Quick Installation (3 Steps Only!)
------------------------------------

[](#-quick-installation-3-steps-only)

```
# 1. Install the package
composer require shammaa/laravel-security

# 2. Publish configuration (optional - everything works automatically)
php artisan vendor:publish --tag=laravel-security-config

# 3. Run migrations (for monitoring and logging)
php artisan migrate
```

🚀 Usage - Super Easy!
---------------------

[](#-usage---super-easy)

### Method 1: 100% Automatic (Easiest)

[](#method-1-100-automatic-easiest)

Just add one middleware in `app/Http/Kernel.php` or `bootstrap/app.php`:

```
// Laravel 11+
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Shammaa\LaravelSecurity\Http\Middleware\SecurityMiddleware::class);
});

// Or Laravel 10
protected $middlewareGroups = [
    'web' => [
        \Shammaa\LaravelSecurity\Http\Middleware\SecurityMiddleware::class,
    ],
];
```

**That's it!** Now all your requests are automatically protected from:

- ✅ **SQL Injection** - Detect and prevent SQL injection attacks
- ✅ **XSS (Cross-Site Scripting)** - Filter malicious scripts and HTML
- ✅ **Command Injection** - Block dangerous system commands
- ✅ **Path Traversal** - Prevent directory traversal attacks (../)
- ✅ **CSRF (Cross-Site Request Forgery)** - Enhanced CSRF protection with token rotation
- ✅ **XXE (XML External Entity)** - Protect against XML external entity attacks
- ✅ **SSRF (Server-Side Request Forgery)** - Block internal network access
- ✅ **IDOR (Insecure Direct Object Reference)** - Validate resource ownership
- ✅ **File Upload Attacks** - Secure file validation with MIME type checking
- ✅ **Brute Force Attacks** - Account lockout after failed attempts
- ✅ **Rate Limiting** - Prevent API abuse and DDoS
- ✅ **Security Headers** - Automatic CSP, HSTS, X-Frame-Options, etc.
- ✅ **Input Sanitization** - Clean all user inputs automatically
- ✅ **IP Blocking** - Auto-block malicious IPs
- ✅ **Security Monitoring** - Log and track all security threats

### Method 2: Using Helper Functions (Very Simple)

[](#method-2-using-helper-functions-very-simple)

```
// Sanitize any input
$clean = security_sanitize($request->input('name'));

// Filter XSS
$safe = security_xss_filter($html);

// Rate Limiting
if (!security_rate_limit('api:' . $userId)) {
    return response()->json(['error' => 'Too many requests'], 429);
}
```

### Method 3: Using Facade (Simplest)

[](#method-3-using-facade-simplest)

```
use Shammaa\LaravelSecurity\Facades\Security;

// Sanitize
$clean = Security::sanitize($input);

// Filter XSS
$safe = Security::xssFilter($html);

// Validate file
if (Security::validateFile($file)) {
    $path = Security::storeFile($file);
}

// Check password strength
$result = Security::checkPassword($password);
if (!$result['valid']) {
    // $result['errors'] contains the errors
}

// Check if account is locked
if (Security::isLocked($email)) {
    return back()->withErrors(['email' => 'Account locked']);
}

// Record failed login attempt
Security::recordFailedLogin($email);

// Clear failed attempts on success
Security::clearFailedLogins($email);
```

📋 Complete Features List
------------------------

[](#-complete-features-list)

### Core Security Protections

[](#core-security-protections)

- ✅ **Automatic Protection** - Just add one middleware and everything works!
- ✅ **SQL Injection Protection** - Detect and prevent SQL injection attacks with pattern matching
- ✅ **XSS Protection** - Filter malicious scripts, iframes, and JavaScript code
- ✅ **Command Injection Protection** - Block dangerous system commands (exec, system, etc.)
- ✅ **Path Traversal Protection** - Prevent directory traversal attacks (../, ..\\)
- ✅ **CSRF Protection** - Enhanced CSRF protection with token rotation and double submit cookie
- ✅ **XXE Protection** - Protect against XML External Entity attacks
- ✅ **SSRF Protection** - Block Server-Side Request Forgery to internal networks
- ✅ **IDOR Protection** - Validate resource ownership and prevent insecure direct object references

### File &amp; Upload Security

[](#file--upload-security)

- ✅ **File Upload Security** - Secure file validation with MIME type and extension checking
- ✅ **Magic Bytes Validation** - Verify file content matches extension
- ✅ **Executable File Blocking** - Automatically block dangerous file types
- ✅ **Secure File Storage** - Automatic file renaming and secure directory storage

### Authentication &amp; Authorization

[](#authentication--authorization)

- ✅ **Brute Force Protection** - Account lockout after failed login attempts
- ✅ **Password Strength Validation** - Enforce strong password policies
- ✅ **Session Security** - Enhanced session protection
- ✅ **Authorization Policies** - Ready-to-use security policies

### Rate Limiting &amp; DDoS Protection

[](#rate-limiting--ddos-protection)

- ✅ **Rate Limiting** - Advanced rate limiting per IP, user, or route
- ✅ **IP Whitelist/Blacklist** - Manage trusted and blocked IPs
- ✅ **Exponential Backoff** - Smart retry logic

### Security Headers

[](#security-headers)

- ✅ **Content Security Policy (CSP)** - Prevent XSS and data injection
- ✅ **Strict Transport Security (HSTS)** - Force HTTPS connections
- ✅ **X-Frame-Options** - Prevent clickjacking attacks
- ✅ **X-Content-Type-Options** - Prevent MIME type sniffing
- ✅ **Referrer-Policy** - Control referrer information
- ✅ **Permissions-Policy** - Control browser features

### Monitoring &amp; Logging

[](#monitoring--logging)

- ✅ **Security Monitoring** - Real-time threat detection and logging
- ✅ **Security Events** - Track all security-related events
- ✅ **IP Blocking** - Automatic IP blocking for repeated threats
- ✅ **Security Reports** - Generate comprehensive security reports
- ✅ **Threat Statistics** - View security statistics and analytics

### Input Validation

[](#input-validation)

- ✅ **Input Sanitization** - Clean all user inputs automatically
- ✅ **HTML Tag Stripping** - Remove dangerous HTML tags
- ✅ **SQL Keyword Filtering** - Remove SQL keywords from inputs
- ✅ **Data Type Validation** - Validate input data types

### Additional Features

[](#additional-features)

- ✅ **Helper Functions** - Easy-to-use helper functions
- ✅ **Facade Support** - Clean API with Facade pattern
- ✅ **Artisan Commands** - Security scanning, reporting, and management
- ✅ **Event System** - Listen to security events
- ✅ **Policy System** - Extensible security policies
- ✅ **Validator Classes** - Reusable validators for all security checks

⚙️ Configuration (Optional)
---------------------------

[](#️-configuration-optional)

Everything works automatically! But if you want to customize, edit `config/security.php`:

```
return [
    // Enable/disable protection
    'sql_injection' => [
        'enabled' => true,  // true = enabled, false = disabled
        'block_on_detect' => true,  // Auto-block on detection
    ],

    'xss' => [
        'enabled' => true,
        'filter_input' => true,  // Filter inputs
    ],

    // Or use .env
    // SECURITY_SQL_INJECTION_ENABLED=true
    // SECURITY_XSS_ENABLED=true
];
```

### Whitelisting Routes for Admin Panels &amp; WYSIWYG Editors

[](#whitelisting-routes-for-admin-panels--wysiwyg-editors)

If you're using admin panels with rich text editors (like CKEditor, TinyMCE) or DataTables, you may need to whitelist certain routes to bypass strict security checks.

#### Option 1: Using Environment Variables (Recommended)

[](#option-1-using-environment-variables-recommended)

Add these to your `.env` file:

```
# Whitelist routes for input sanitization (comma-separated)
SECURITY_INPUT_WHITELIST_ROUTES=admin/*,dashboard/posts/create,dashboard/posts/edit

# Whitelist specific parameters that should not be sanitized
SECURITY_INPUT_WHITELIST_PARAMS=content,description,body,html,editor_content

# Whitelist routes for XSS filtering (for WYSIWYG editors)
SECURITY_XSS_WHITELIST_ROUTES=admin/*,dashboard/*

# Whitelist routes for security headers (for admin panels)
SECURITY_HEADERS_WHITELIST_ROUTES=admin/*,dashboard/*
```

#### Option 2: Using Config File

[](#option-2-using-config-file)

Edit `config/security.php`:

```
'input' =&gt; [
    'whitelist_routes' =&gt; ['admin/*', 'dashboard/posts/*'],
    'whitelist_parameters' =&gt; ['content', 'description', 'body', 'html'],
],

'xss' =&gt; [
    'whitelist_routes' =&gt; ['admin/*', 'dashboard/*'],
],

'headers' =&gt; [
    'whitelist_routes' =&gt; ['admin/*', 'dashboard/*'],
],
```

#### Example: CKEditor Setup

[](#example-ckeditor-setup)

```
# For CKEditor to work properly
SECURITY_INPUT_WHITELIST_PARAMS=content,description,article_body
SECURITY_XSS_WHITELIST_ROUTES=admin/articles/*,admin/pages/*
SECURITY_HEADERS_WHITELIST_ROUTES=admin/*

# Make CSP more permissive for admin panel
SECURITY_HEADER_CSP="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' cdn.ckeditor.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:;"
```

#### Example: DataTables Setup

[](#example-datatables-setup)

```
# For DataTables with server-side processing
SECURITY_HEADERS_WHITELIST_ROUTES=admin/datatables/*,api/datatables/*
```

**Important Notes:**

- Whitelist only admin routes that you trust
- Use specific route patterns instead of wildcards when possible
- Always validate user permissions before allowing access to whitelisted routes
- Consider using middleware groups for better organization

### Excluding Routes from All Security Checks

[](#excluding-routes-from-all-security-checks)

If you have routes that need to completely bypass **all** security checks (e.g., AI APIs, webhooks, large content uploads), you can use the `excluded_routes` feature:

#### Option 1: Using Environment Variables (Recommended)

[](#option-1-using-environment-variables-recommended-1)

Add this to your `.env` file:

```
# Exclude routes from ALL security checks (comma-separated)
SECURITY_EXCLUDED_ROUTES=api/ai/*,api/webhooks/*,api/external/*
```

#### Option 2: Using Config File

[](#option-2-using-config-file-1)

Edit `config/security.php`:

```
'excluded_routes' => ['api/ai/*', 'api/webhooks/*', 'api/external/*'],
```

#### When to Use Excluded Routes

[](#when-to-use-excluded-routes)

Use `excluded_routes` when:

- ✅ Sending large content to AI APIs (e.g., long text, recipes, articles)
- ✅ Receiving webhooks from external services
- ✅ Handling file uploads with custom validation
- ✅ Processing data that may contain SQL-like keywords or special characters

**⚠️ Security Warning:**

- Only exclude routes that you absolutely trust
- Implement your own validation for excluded routes
- Never exclude user-facing routes without proper authentication
- Use specific patterns instead of broad wildcards

#### Example: AI API Integration

[](#example-ai-api-integration)

```
// .env
SECURITY_EXCLUDED_ROUTES=api/ai/*

// Now your AI routes won't be blocked
Route::post('/api/ai/rewrite', [AIController::class, 'rewrite']);
Route::post('/api/ai/generate', [AIController::class, 'generate']);
```

🛠️ Commands
-----------

[](#️-commands)

### Security Scan

[](#security-scan)

```
php artisan security:scan
php artisan security:scan --fix  # Attempt to fix issues
```

### Generate Security Report

[](#generate-security-report)

```
php artisan security:report
php artisan security:report --days=60 --format=table
```

### Unblock IP

[](#unblock-ip)

```
php artisan security:unblock 192.168.1.1
```

### Clean Security Logs

[](#clean-security-logs)

```
php artisan security:clean --days=30
php artisan security:clean --days=30 --force  # Without confirmation
```

💡 Practical Examples
--------------------

[](#-practical-examples)

### Example 1: File Upload Security (Super Easy!)

[](#example-1-file-upload-security-super-easy)

```
// In Controller
public function upload(Request $request)
{
    $file = $request->file('document');

    // Simple way - Helper Function
    if (!security_validate_file($file)) {
        return back()->withErrors(['file' => 'File not allowed']);
    }

    // Secure storage
    $path = security_store_file($file);

    // Or use Facade
    if (Security::validateFile($file)) {
        $path = Security::storeFile($file);
    }

    return response()->json(['path' => $path]);
}
```

### Example 2: Rate Limiting for API

[](#example-2-rate-limiting-for-api)

```
// In Controller or Middleware
public function apiEndpoint(Request $request)
{
    $userId = auth()->id();

    // Rate limit: 100 requests per minute
    if (!Security::rateLimit("api:{$userId}", 100, 1)) {
        return response()->json([
            'error' => 'Too many requests'
        ], 429);
    }

    // Rest of the code...
}
```

### Example 3: Brute Force Protection (Super Easy!)

[](#example-3-brute-force-protection-super-easy)

```
// In LoginController
public function login(Request $request)
{
    $email = $request->email;

    // Simple way - Helper Functions
    if (security_is_locked($email)) {
        return back()->withErrors(['email' => 'Account locked. Try again later.']);
    }

    if (!Auth::attempt($request->only('email', 'password'))) {
        // Record failed attempt
        security_record_failed_login($email);
        return back()->withErrors(['email' => 'Invalid credentials']);
    }

    // Success - clear failed attempts
    security_clear_failed_logins($email);

    return redirect('/dashboard');

    // Or use Facade
    // if (Security::isLocked($email)) { ... }
    // Security::recordFailedLogin($email);
    // Security::clearFailedLogins($email);
}
```

### Example 4: Manual Input Sanitization

[](#example-4-manual-input-sanitization)

```
// Sanitize any input
$name = security_sanitize($request->input('name'));
$email = security_sanitize($request->input('email'));

// Or use Facade
$name = Security::sanitize($request->input('name'));
```

### Example 5: Filter Output from XSS

[](#example-5-filter-output-from-xss)

```
// In Blade
{!! Security::xssFilter($user->bio) !!}

// Or Helper
{!! security_xss_filter($user->bio) !!}
```

📚 More Information
------------------

[](#-more-information)

### Policies

[](#policies)

The package includes ready-to-use policies that you can customize:

- `SecurityPolicy` - General security operations
- `FileUploadPolicy` - File upload permissions
- `ApiSecurityPolicy` - API access control
- `AdminSecurityPolicy` - Admin operations

### Events

[](#events)

The package fires events when threats are detected:

- `SecurityThreatDetected` - When any threat is detected
- `SqlInjectionAttempt` - SQL injection attempt
- `XssAttempt` - XSS attempt
- `BruteForceAttempt` - Brute force attack
- `UnauthorizedAccessAttempt` - Unauthorized access attempt

You can listen to these events:

```
use Shammaa\LaravelSecurity\Events\SecurityThreatDetected;

Event::listen(SecurityThreatDetected::class, function ($event) {
    // Send email, notification, etc...
    Mail::to('admin@example.com')->send(new SecurityAlert($event));
});
```

🎯 Summary
---------

[](#-summary)

**Basic Usage:**

1. Install the package
2. Add one middleware
3. Done! Everything works automatically

**For Advanced Users:**

- Use Helper Functions or Facade
- Customize settings in `config/security.php`
- Use Commands for monitoring and reports

📄 License
---------

[](#-license)

MIT

👤 Author
--------

[](#-author)

Shadi Shammaa

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance75

Regular maintenance activity

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Every ~2 days

Total

5

Last Release

137d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/092a8b57ed995393618ee9dbf2055d43060fef84a2c5b4ef4e305bab3ff5b432?d=identicon)[shadishammaa](/maintainers/shadishammaa)

---

Top Contributors

[![shammaa](https://avatars.githubusercontent.com/u/8601466?v=4)](https://github.com/shammaa "shammaa (7 commits)")

---

Tags

laravelmonitoringsecurityAuthenticationauthorizationxsscsrfSQL Injectionrate limitingfile-uploadsecurity-headerspolicies

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/shammaa-laravel-security/health.svg)

```
[![Health](https://phpackages.com/badges/shammaa-laravel-security/health.svg)](https://phpackages.com/packages/shammaa-laravel-security)
```

###  Alternatives

[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

416632.8k5](/packages/yadahan-laravel-authentication-log)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)[wnikk/laravel-access-rules

Simple system of ACR (access control rules) for Laravel, with roles, groups, unlimited inheritance and possibility of multiplayer use.

103.6k1](/packages/wnikk-laravel-access-rules)

PHPackages © 2026

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