Comprehensive Setup

AIWAF-PHP Comprehensive Setup Guide

Source and package versions

One AIWAF repository. Python: py/aiwaf/ · Node.js: js/ · Rust/WASM: rust/ · Java: java/. Source and canonical README. Versions shown describe the source checkout; package releases are independent. Current Python/Node source targets are aiwaf 1.1.8 (Python) and aiwaf 1.1.5 (npm), with Rust/Python 0.2.7 and WASM 0.2.5 and Java 1.3.5. Sandbox guides retain their separately pinned builds.

1. What This Guide Is

This is an end-to-end setup manual for running aiwaf-php in real PHP applications.

  • Environment prerequisites.
  • Installation for app usage and repository development.
  • Integration patterns for plain PHP, Laravel, Symfony, and WordPress style bootstraps.
  • Baseline and production-oriented configuration.
  • Storage/backend selection for rate limiting.
  • Training workflow and verification.
  • Troubleshooting and validation playbooks.

2. Prerequisites

2.1 Runtime

  • PHP >= 7.4
  • Composer
  • Optional ext-redis when using Redis adapter/driver

2.2 System dependencies

  • Writable filesystem for resources/ runtime artifacts.
  • Access to application/proxy logs for training (AIWAF_ACCESS_LOG).

2.3 Recommended for production

  • Persistent storage for runtime artifacts and model files.
  • Scheduled training runs (php cli/detect_and_train.php).
  • Known route/path hints configured to reduce false positives.

3. Installation Paths

# Application install
composer require aayushgauba/aiwaf

# Local development in this repository
composer install

# Initialize runtime resources
php setup.php

4. Core Configuration Concepts

AIWAF-PHP can be configured through static config, runtime config, and env mapping in RuntimeConfig::loadFromEnvironment().

  • Header validation: AIWAF_HEADER_VALIDATION_ENABLED, AIWAF_HEADER_BLOCK_SUSPICIOUS, AIWAF_HEADER_QUALITY_THRESHOLD, AIWAF_HEADER_EXEMPT_PATHS
  • Rate limiting: AIWAF_RATE_LIMITING_ENABLED, AIWAF_RATE_MAX_REQUESTS, AIWAF_RATE_WINDOW_SECONDS, AIWAF_EXEMPT_IPS
  • Detection toggles: IP/keyword, honeypot, AI anomaly, UUID tamper toggles
  • Geo policy: allow/block countries
  • Training controls: access log, thresholds, force/disable flags, anomaly threshold, known paths

5. Auto Middleware & Path Manifest Setup

AIWAF-PHP can automatically tune your middleware protections based on your application's routing structure. By generating a Path Manifest, AIWAF categorizes your endpoints (e.g., API vs HTML Form) and automatically disables unnecessary middlewares (like Honeypots for APIs) and enforces strict rate limits where appropriate.

# Generate the path manifest automatically
php cli/detect_and_train.php --generate-manifest

At startup, AIWAF reads the manifest from .aiwaf/paths.json to auto-configure the execution chain.

If you prefer fine-grained manual control over your middleware stack rather than relying on auto-generation, proceed to the framework-specific "All Middlewares" manual setup sections below.

6. Framework Setup (All Middlewares)

Laravel

Use patterns under examples/laravel/ (service provider + train command).

AIWAF::setPathExistsResolver(function (string $path): bool {
    $candidate = '/' . ltrim((string) strtok($path, '?'), '/');
    foreach (Route::getRoutes() as $route) {
        $uri = '/' . ltrim($route->uri(), '/');
        if ($candidate === $uri || strpos($candidate, $uri . '/') === 0) {
            return true;
        }
    }
    return false;
});

8. Storage Setup and Backend Choices

7.1 Default behavior

  • Core runtime artifacts are file-backed under resources/.
  • php setup.php ensures base files exist.

7.2 Key artifact files

  • resources/blocked_ips.json
  • resources/dynamic_keywords.json
  • resources/request_features.csv
  • resources/forest_model.json

7.3 Rate-limit adapter/backend options

  • In-memory adapter
  • APCu adapter
  • Redis adapter
  • DB adapter

9. Training Setup

8.1 Configure training log source

# Linux/macOS
export AIWAF_ACCESS_LOG=/var/log/nginx/access.log

# PowerShell
$env:AIWAF_ACCESS_LOG = "C:\path\to\access.log"

8.2 Run training

php cli/detect_and_train.php

8.3 Useful training env examples

AIWAF_MIN_TRAIN_LOGS=50
AIWAF_MIN_AI_LOGS=10000
AIWAF_FORCE_AI_TRAINING=false
AIWAF_DISABLE_AI=false
AIWAF_AI_ANOMALY_THRESHOLD=0.65
AIWAF_KNOWN_PATHS=/app,/api,/wp-json

8.4 Expected output

  • Updated keyword store and model artifact when thresholds are met.
  • Trainer telemetry via logs and AIWAF::getLastTrainingTelemetry().

10. Optional GeoIP Enablement

AIWAF_GEO_BLOCK_ENABLED=true
AIWAF_GEO_BLOCK_COUNTRIES=CN,RU
# or allowlist mode
AIWAF_GEO_ALLOW_COUNTRIES=US,CA

Geo checks run in AIWAF::protect() when enabled.

11. Optional Redis/APCu Setup

10.1 Redis adapter example

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
RateLimiter::initAdapter(new RedisAdapter($redis));

10.2 APCu adapter example

RateLimiter::initAdapter(new ApcuAdapter());

12. Production Baseline Checklist

  • [ ] Package installed and app starts with AIWAF enabled.
  • [ ] php setup.php executed in target environment.
  • [ ] Exempt paths set for health/static/known-safe callbacks.
  • [ ] Rate limits tuned from real traffic patterns.
  • [ ] Header policy tuned to reduce false positives.
  • [ ] Training job scheduled and verified.
  • [ ] Intentional block scenario validated in staging.
  • [ ] Runtime artifact paths persisted across deploys/restarts.

13. Validation Playbook

  1. Smoke checks: health/static pass, suspicious probe blocks.
  2. Rate-limit checks: burst traffic transitions to 429 and/or IP block.
  3. Header checks: low-quality headers trigger expected behavior.
  4. Training checks: confirm log readability and artifact/telemetry updates.

14. Troubleshooting

  • Training skipped: verify log path/readability and thresholds.
  • Too many false positives: tune exemptions/known paths and anomaly threshold.
  • Not enough detections: lower anomaly threshold carefully and retrain with representative traffic.
  • Redis/APCu issues: verify extension availability/connectivity and fallback to in-memory temporarily.
  • Resource permissions: ensure read/write on resources/, rerun php setup.php.

15. Contributor Setup (Repository)

composer install
composer test

php setup.php
php cli/detect_and_train.php
composer run cover-everything
composer run test-adapters-matrix
composer run validate-all

Suggested docs: README.md.