PHP code example of zxf / security

1. Go to this page and download the library: Download zxf/security library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zxf / security example snippets


// bootstrap/app.php
use Illuminate\Foundation\Configuration\Middleware;

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\zxf\Security\Middleware\SecurityMiddleware::class);
})

   return [
       // ... 其他中间件
       \zxf\Security\Middleware\SecurityMiddleware::class,
   ];
   

   \zxf\Security\Providers\ThinkPHPSecurityServiceProvider::register($this->app);
   

// config/security.php
'custom_patterns' => [
    'high_risk' => [base_path('security/custom_sql_rules.php')],
    'xss'       => [base_path('security/custom_xss_rules.php')],
    'url_path'  => [base_path('security/custom_path_rules.php')],
],

// security/custom_sql_rules.php
return [
    'sql' => [
        ['pattern' => '/your_custom_sql_pattern/i', 'risk' => 'high'],
    ],
    'my_custom_type' => [
        ['pattern' => '/custom_regex/i', 'risk' => 'medium'],
    ],
];

// config/security.php

'before_block_callback' => function(\zxf\Security\Dto\InterceptionContext $context) {
    // 1. 记录到数据库
    SecurityLog::create($context->toArray());

    // 2. 低风险请求自动放行
    if ($context->getRiskLevel() === 'low') {
        return false; // 放行
    }

    // 3. 特定IP段放行
    if (str_starts_with($context->clientIp, '192.168.')) {
        return false;
    }

    // 4. 发送告警(异步队列)
    SecurityAlertJob::dispatch($context);

    return true; // 拦截
},

$context->threatType           // 威胁类型: sql, xss, command, blacklist...
$context->getThreatTypeDescription() // 中文描述
$context->getRiskLevel()       // 风险等级: high, medium, low
$context->clientIp             // 客户端IP
$context->method               // HTTP方法
$context->url                  // 请求URL
$context->matchedPattern       // 匹配的正则模式
$context->matchedContent       // 匹配的内容片段(脱敏)
$context->allThreats           // 所有检测到的威胁
$context->toArray()            // 转为数组格式

// config/security.php
'response' => [
    'view' => 'errors.security',
],

'response' => [
    'view' => function($data) {
        // 根据威胁类型返回不同视图
        if (in_array('sql', $data['threats'])) {
            return view('errors.sql-injection', $data);
        }
        return view('errors.generic', $data);
    },
],
bash
# 发布配置文件
php artisan vendor:publish --tag=security-config