PHPackages                             laikait/laika-shield - 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. [Security](/categories/security)
4. /
5. laikait/laika-shield

ActivePackage[Security](/categories/security)

laikait/laika-shield
====================

A powerful firewall middleware package for the Laika PHP Framework — IP filtering, rate limiting, SQL injection &amp; XSS detection, and request filtering.

v1.0.0(3w ago)0115↓100%MITPHPPHP &gt;=8.1CI passing

Since Mar 3Pushed 2w agoCompare

[ Source](https://github.com/laikait/laika-shield)[ Packagist](https://packagist.org/packages/laikait/laika-shield)[ RSS](/packages/laikait-laika-shield/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (1)Versions (3)Used By (0)

🛡️ Laika Shield
===============

[](#️-laika-shield)

**Laika Shield** is a powerful, zero-dependency firewall middleware for the [Laika PHP Framework](https://github.com/laikait/laika-framework).

[![Tests](https://github.com/laikait/laika-shield/actions/workflows/tests.yml/badge.svg)](https://github.com/laikait/laika-shield/actions)[![PHP](https://camo.githubusercontent.com/7535257ca228724c93658bd52583d4e47a9bab02c356abf6e54c1d575f2151e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c75652e737667)](https://php.net)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

---

✨ Features
----------

[](#-features)

FeatureDescription🚫 IP BlockingBlock individual IPs or CIDR ranges✅ IP AllowlistingRestrict access to specific IPs/ranges only🔢 IP Version FilteringAllow only IPv4 or only IPv6 connections⏱️ Rate LimitingLimit requests per IP per time window💉 SQL Injection DetectionBlock common SQLi attack payloads🐛 XSS DetectionBlock cross-site scripting attempts🔍 Request FilteringFilter by HTTP method, URI, User-Agent, headers, and body size---

📦 Installation
--------------

[](#-installation)

```
composer require laikait/laika-shield
```

---

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Publish the config file

[](#1-publish-the-config-file)

Copy `vendor/laikait/laika-shield/src/Config/shield.php` to your project's `config/` directory.

### 2. Register as Middleware

[](#2-register-as-middleware)

In your Laika application bootstrap or middleware pipeline:

```
use Laika\Shield\Http\ShieldMiddleware;

$config = require __DIR__ . '/../config/shield.php';

$middleware = new ShieldMiddleware($config);
$middleware->handle(function () {
    // Your controller / next middleware
});
```

### 3. Or use the static API

[](#3-or-use-the-static-api)

```
use Laika\Shield\Shield;

Shield::boot(require 'config/shield.php');
```

### 4. Or use the fluent builder

[](#4-or-use-the-fluent-builder)

```
use Laika\Shield\Shield;

(new Shield())
    ->trustProxy()
    ->blockIps(['1.2.3.4', '10.10.0.0/16'])
    ->allowIps(['203.0.113.0/24'])
    ->requireIpVersion(4) // IPv4 only
    ->rateLimit(maxHits: 100, windowSecs: 60)
    ->detectSqlInjection(skipKeys: ['password'])
    ->detectXss(skipKeys: ['html_content'])
    ->filterRequests(
        blockedMethods: ['TRACE', 'CONNECT'],
        blockedUserAgentPatterns: ['/sqlmap/i', '/nikto/i'],
    )
    ->run();
```

---

⚙️ Configuration Reference
--------------------------

[](#️-configuration-reference)

```
// config/shield.php
return [

    // Trust proxy headers (X-Forwarded-For, CF-Connecting-IP, etc.)
    'trust_proxy' => false,

    // IP blocking and allowlisting
    'ip' => [
        'blocklist' => ['1.2.3.4', '192.168.100.0/24'],
        'allowlist' => [],  // when non-empty, ONLY these IPs are allowed
    ],

    // Only allow IPv4 (4) or IPv6 (6). null = both allowed.
    'ip_version' => null,

    // Rate limiting
    'rate_limit' => [
        'max_hits'    => 60,    // requests
        'window'      => 60,    // seconds
        'storage_dir' => null,  // defaults to sys_get_temp_dir()
    ],

    // SQL injection detection
    'sql_injection' => [
        'skip_keys' => [],      // input keys to skip
        'scan_body' => true,    // also scan raw body (JSON, XML)
    ],

    // XSS detection
    'xss' => [
        'skip_keys'    => [],
        'scan_headers' => false,
        'scan_body'    => true,
    ],

    // Request filtering
    'request_filter' => [
        'blocked_methods'        => ['TRACE', 'CONNECT'],
        'blocked_uri_patterns'   => ['/\/\.env$/i'],
        'blocked_user_agents'    => ['/sqlmap/i', '/nikto/i'],
        'required_headers'       => [],
        'blocked_header_values'  => [],
        'max_content_length'     => null,
        'min_content_length'     => null,
    ],
];
```

---

🏗️ Architecture
---------------

[](#️-architecture)

```
src/
├── Shield.php                          # Main firewall engine (static + fluent API)
├── Interfaces/
│   ├── FirewallInterface.php           # Core Firewall Interface
│   ├── RuleInterface.php              # Individual Rule Interface
│   └── DetectorInterface.php          # Pattern Detector Interface
├── Rules/
│   ├── IpRule.php                     # IP blocking / allowlisting
│   ├── IpVersionRule.php              # IPv4 / IPv6 enforcement
│   ├── RateLimitRule.php              # Rate limiting
│   ├── SqlInjectionRule.php           # SQL injection protection
│   ├── XssRule.php                    # XSS protection
│   └── RequestFilterRule.php          # General request filtering
├── Detectors/
│   ├── SqlInjectionDetector.php       # SQLi regex patterns engine
│   └── XssDetector.php                # XSS regex patterns engine
├── Http/
│   └── ShieldMiddleware.php           # Laika MMC middleware integration
├── Support/
│   ├── IpHelper.php                   # IP validation, CIDR, version detection
│   ├── RateLimiter.php                # File-based rate limit store
│   └── RequestHelper.php             # Request data extraction helpers
├── Exceptions/
│   ├── FirewallException.php          # Base firewall exception (HTTP 403)
│   └── RateLimitExceededException.php # Rate limit exception (HTTP 429)
└── Config/
    └── shield.php                     # Default configuration template

```

---

🔌 Writing Custom Rules
----------------------

[](#-writing-custom-rules)

Implement `RuleInterface` to create your own firewall rules:

```
use Laika\Shield\Interfaces\RuleInterface;

class CountryBlockRule implements RuleInterface
{
    public function passes(): bool
    {
        // Your logic here
        return true;
    }

    public function message(): string
    {
        return 'Access denied from your country.';
    }
}

// Register it
(new Shield())
    ->addRule(new CountryBlockRule())
    ->run();
```

---

🧪 Running Tests
---------------

[](#-running-tests)

```
composer install
vendor/bin/phpunit
```

---

🌐 IP Version Detection
----------------------

[](#-ip-version-detection)

Shield exposes `IpHelper` for standalone IP utilities:

```
use Laika\Shield\Support\IpHelper;

IpHelper::version('8.8.8.8');          // 4
IpHelper::version('2001:db8::1');      // 6
IpHelper::version('invalid');          // null

IpHelper::isV4('192.168.1.1');         // true
IpHelper::isV6('::1');                 // true
IpHelper::isPrivate('10.0.0.1');       // true
IpHelper::isLoopback('127.0.0.1');     // true
IpHelper::inCidr('192.168.1.5', '192.168.1.0/24'); // true

// Resolve real client IP (proxy-aware)
$ip = IpHelper::resolve(trustProxy: true);
```

---

📄 License
---------

[](#-license)

MIT © [Laika IT](https://github.com/laikait)

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance96

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

21d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7272cd554fe8bf859b8450494f244927ee210cd95d516325fda55d33c74e5886?d=identicon)[riyadhtayf](/maintainers/riyadhtayf)

---

Top Contributors

[![laikait](https://avatars.githubusercontent.com/u/100719384?v=4)](https://github.com/laikait "laikait (17 commits)")

---

Tags

firewallfirewall-managementlaikasecuritywafphpmiddlewaresecurityxssSQL Injectionfirewallrate limitingip-blockinglaika

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/laikait-laika-shield/health.svg)

```
[![Health](https://phpackages.com/badges/laikait-laika-shield/health.svg)](https://phpackages.com/packages/laikait-laika-shield)
```

###  Alternatives

[akaunting/laravel-firewall

Web Application Firewall (WAF) package for Laravel

1.0k453.9k2](/packages/akaunting-laravel-firewall)

PHPackages © 2026

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