PHP 安全中心功能

wen PHP项目 3

本文目录导读:

PHP 安全中心功能

  1. 安全中心主类
  2. 表单验证类
  3. 使用示例
  4. 数据库安全类
  5. 安全配置文件
  6. 安全监控脚本

我来为您设计一个完整的PHP安全中心功能,包含多种安全防护机制。

安全中心主类

<?php
/**
 * 安全中心类
 * 提供全面的安全防护功能
 */
class SecurityCenter {
    private static $instance = null;
    private $config;
    private $logPath;
    private $blockedIPs = [];
    // 配置项
    private $defaultConfig = [
        'enable_html_filter' => true,
        'enable_sql_filter' => true,
        'enable_xss_filter' => true,
        'enable_csrf_filter' => true,
        'enable_sql_injection_protection' => true,
        'enable_file_upload_protection' => true,
        'max_attempts' => 5,          // 最大尝试次数
        'lockout_time' => 900,         // 锁定时间(秒)
        'session_timeout' => 1800,     // 会话超时时间
        'log_security_events' => true,
        'whitelist_ips' => [],
        'blacklist_ips' => [],
        'allowed_extensions' => ['jpg', 'jpeg', 'png', 'gif', 'pdf']
    ];
    private function __construct() {
        $this->config = $this->defaultConfig;
        $this->logPath = __DIR__ . '/../logs/security/';
        $this->initLogDirectory();
        $this->loadBlockedIPs();
    }
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    /**
     * 初始化日志目录
     */
    private function initLogDirectory() {
        if (!is_dir($this->logPath)) {
            mkdir($this->logPath, 0755, true);
        }
    }
    /**
     * 加载被封禁的IP列表
     */
    private function loadBlockedIPs() {
        $blockedFile = $this->logPath . 'blocked_ips.json';
        if (file_exists($blockedFile)) {
            $this->blockedIPs = json_decode(file_get_contents($blockedFile), true);
        }
        // 合并配置中的黑名单
        $this->blockedIPs = array_merge($this->blockedIPs, $this->config['blacklist_ips']);
    }
    /**
     * 运行安全防护
     */
    public function run() {
        // IP安全检查
        $this->checkIP();
        // 请求过滤
        $this->filterRequest();
        // 初始化安全会话
        $this->initSecureSession();
        // 添加安全头
        $this->setSecurityHeaders();
        // CSRF防护
        if ($this->config['enable_csrf_filter']) {
            $this->validateCSRFToken();
        }
    }
    /**
     * IP安全检查
     */
    private function checkIP() {
        $currentIP = $this->getClientIP();
        // 检查IP是否被封禁
        if (in_array($currentIP, $this->blockedIPs)) {
            http_response_code(403);
            die('您的IP已被禁止访问');
        }
        // 检查IP白名单
        if (!empty($this->config['whitelist_ips']) && 
            !in_array($currentIP, $this->config['whitelist_ips'])) {
            http_response_code(403);
            die('IP不在允许访问范围内');
        }
        // 检测异常请求频率
        $this->checkRequestFrequency($currentIP);
    }
    /**
     * 获取客户端IP
     */
    private function getClientIP() {
        $ips = [];
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ips[] = $_SERVER['HTTP_CLIENT_IP'];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = array_merge($ips, explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
        }
        $ips[] = $_SERVER['REMOTE_ADDR'] ?? '';
        foreach ($ips as $ip) {
            $ip = trim($ip);
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
                return $ip;
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    }
    /**
     * 检查请求频率
     */
    private function checkRequestFrequency($ip) {
        $sessionKey = 'request_count_' . md5($ip);
        $timeKey = 'request_time_' . md5($ip);
        if (!isset($_SESSION[$sessionKey])) {
            $_SESSION[$sessionKey] = 1;
            $_SESSION[$timeKey] = time();
        } else {
            $timeDiff = time() - $_SESSION[$timeKey];
            if ($timeDiff > $this->config['session_timeout']) {
                $_SESSION[$sessionKey] = 1;
                $_SESSION[$timeKey] = time();
            } else {
                $_SESSION[$sessionKey]++;
                if ($_SESSION[$sessionKey] > $this->config['max_attempts'] * 10) {
                    $this->blockIP($ip);
                    $this->logSecurityEvent('high_requests', $ip, 
                        'Request frequency exceeded');
                }
            }
        }
    }
    /**
     * 封禁IP
     */
    private function blockIP($ip) {
        $blockedFile = $this->logPath . 'blocked_ips.json';
        $this->blockedIPs[$ip] = time() + $this->config['lockout_time'];
        file_put_contents($blockedFile, json_encode($this->blockedIPs));
    }
    /**
     * 请求过滤
     */
    private function filterRequest() {
        // SQL注入防护
        if ($this->config['enable_sql_injection_protection']) {
            $this->filterSQLInjection();
        }
        // XSS防护
        if ($this->config['enable_xss_filter']) {
            $this->filterXSS();
        }
        // HTML过滤
        if ($this->config['enable_html_filter']) {
            $this->filterHTML();
        }
    }
    /**
     * SQL注入过滤
     */
    private function filterSQLInjection() {
        $patterns = [
            '/\b(select|insert|update|delete|drop|union|alter|create|rename|truncate|replace)\b.*\b(from|into|set|table)\b/i',
            '/\b(union.*select|load_file|outfile)\b/i',
            '/\b(and|or)\s+[0-9]+\s*=\s*[0-9]+\b/i',
            '/\b(and|or)\s*\'\s*=\s*\'\b/i',
            '/\b(and|or)\s*\`\s*=\s*\`\b/i',
            '/\b(and|or)\s*"/"s*=\s*"/"s*/i',
            '/--/i',
            '/\b(benchmark|sleep|waitfor)\s*\(/i'
        ];
        foreach ($_REQUEST as $key => $value) {
            if (is_string($value)) {
                foreach ($patterns as $pattern) {
                    if (preg_match($pattern, $value)) {
                        $this->logSecurityEvent('sql_injection', $this->getClientIP(), 
                            "SQL Injection attempt: " . $key);
                        http_response_code(403);
                        die('非法SQL注入行为');
                    }
                }
            }
        }
    }
    /**
     * XSS过滤
     */
    private function filterXSS() {
        $xssPatterns = [
            '/<script.*?>.*?<\/script>/is',
            '/javascript:/i',
            '/on(click|load|error|mouseover|focus|blur)\s*=/i',
            '/<iframe.*?>.*?<\/iframe>/is',
            '/<object.*?>.*?<\/object>/is',
            '/<embed.*?>.*?<\/embed>/is',
            '/expression\s*\(/i',
            '/vbscript:/i'
        ];
        foreach ($_REQUEST as $key => $value) {
            if (is_string($value)) {
                foreach ($xssPatterns as $pattern) {
                    if (preg_match($pattern, $value)) {
                        $this->logSecurityEvent('xss_attack', $this->getClientIP(), 
                            "XSS attack attempt: " . $key);
                        // 清理XSS内容
                        $_REQUEST[$key] = $this->cleanXSS($value);
                    }
                }
            }
        }
    }
    /**
     * 清理XSS内容
     */
    private function cleanXSS($data) {
        // 移除脚本
        $data = preg_replace('/<script.*?>/is', '', $data);
        $data = preg_replace('/<\/script>/is', '', $data);
        // 移除事件处理
        $data = preg_replace('/\son[a-z]+\s*=\s*(["\']).*?\1/i', '', $data);
        // 移除javascript协议
        $data = str_ireplace('javascript:', '', $data);
        // HTML实体编码
        $data = htmlentities($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
    /**
     * HTML过滤
     */
    private function filterHTML() {
        $allowedTags = '<p><br><b><i><strong><em><ul><ol><li><a><h1><h2><h3><h4>";
        foreach ($_REQUEST as $key => $value) {
            if (is_string($value)) {
                $_REQUEST[$key] = strip_tags($value, $allowedTags);
            }
        }
    }
    /**
     * 初始化安全会话
     */
    private function initSecureSession() {
        // 设置安全会话属性
        session_name('SECURE_SESSION');
        session_start();
        // 会话超时检查
        if (isset($_SESSION['last_activity']) && 
            (time() - $_SESSION['last_activity'] > $this->config['session_timeout'])) {
            $this->logout();
        }
        $_SESSION['last_activity'] = time();
        // 会话固定攻击防护
        if (!isset($_SESSION['session_started'])) {
            session_regenerate_id(true);
            $_SESSION['session_started'] = true;
        }
    }
    /**
     * 设置安全响应头
     */
    private function setSecurityHeaders() {
        header('X-Frame-Options: DENY');
        header('X-XSS-Protection: 1; mode=block');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'");
        header('X-Permitted-Cross-Domain-Policies: none');
        header('Feature-Policy: vibrate \'self\'; microphone \'none\'; geolocation \'none\'');
    }
    /**
     * CSRF Token生成
     */
    public function generateCSRFToken() {
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }
    /**
     * 验证CSRF Token
     */
    public function validateCSRFToken() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $token = $_POST['csrf_token'] ?? '';
            if (!hash_equals($_SESSION['csrf_token'], $token)) {
                $this->logSecurityEvent('csrf_attack', $this->getClientIP(), 
                    'Invalid CSRF token');
                http_response_code(403);
                die('CSRF Token验证失败');
            }
        }
    }
    /**
     * 文件上传安全验证
     */
    public function validateFileUpload($file) {
        if (!$this->config['enable_file_upload_protection']) {
            return true;
        }
        // 检查文件大小
        if ($file['size'] > 5 * 1024 * 1024) { // 5MB
            return ['error' => '文件太大'];
        }
        // 检查文件类型
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $this->config['allowed_extensions'])) {
            return ['error' => '不允许的文件类型'];
        }
        // 检查MIME类型
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        $allowedMimes = [
            'image/jpeg' => ['jpg', 'jpeg'],
            'image/png' => ['png'],
            'image/gif' => ['gif'],
            'application/pdf' => ['pdf']
        ];
        if (!isset($allowedMimes[$mimeType])) {
            return ['error' => '无效的MIME类型'];
        }
        if (!in_array($extension, $allowedMimes[$mimeType])) {
            return ['error' => '文件扩展名与MIME类型不匹配'];
        }
        return true;
    }
    /**
     * 密码强度验证
     */
    public function validatePasswordStrength($password) {
        $score = 0;
        // 长度检查
        if (strlen($password) >= 8) $score++;
        if (strlen($password) >= 12) $score++;
        // 包含大写字母
        if (preg_match('/[A-Z]/', $password)) $score++;
        // 包含小写字母
        if (preg_match('/[a-z]/', $password)) $score++;
        // 包含数字
        if (preg_match('/[0-9]/', $password)) $score++;
        // 包含特殊字符
        if (preg_match('/[^a-zA-Z0-9]/', $password)) $score++;
        return $score >= 4 ? true : false;
    }
    /**
     * 记录安全事件
     */
    private function logSecurityEvent($type, $ip, $detail = '') {
        if (!$this->config['log_security_events']) return;
        $logFile = $this->logPath . date('Y-m-d') . '.log';
        $message = sprintf(
            "[%s] Type: %s | IP: %s | Detail: %s | URI: %s\n",
            date('Y-m-d H:i:s'),
            $type,
            $ip,
            $detail,
            $_SERVER['REQUEST_URI'] ?? 'Unknown'
        );
        file_put_contents($logFile, $message, FILE_APPEND);
    }
    /**
     * 数据加密
     */
    public function encryptData($data, $key) {
        $cipher = "aes-256-cbc";
        $ivLength = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivLength);
        $encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }
    /**
     * 数据解密
     */
    public function decryptData($encryptedData, $key) {
        $cipher = "aes-256-cbc";
        $data = base64_decode($encryptedData);
        $ivLength = openssl_cipher_iv_length($cipher);
        $iv = substr($data, 0, $ivLength);
        $encrypted = substr($data, $ivLength);
        return openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
    }
    /**
     * 登出
     */
    public function logout() {
        $_SESSION = [];
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
        header('Location: /login.php');
        exit;
    }
    /**
     * 获取安全中心状态
     */
    public function getSecurityStatus() {
        return [
            'config' => $this->config,
            'ip' => $this->getClientIP(),
            'csrf_token' => $this->generateCSRFToken(),
            'session_timeout' => $this->config['session_timeout'],
            'blocked_ips_count' => count($this->blockedIPs)
        ];
    }
    public function __clone() {}
    public function __wakeup() {}
}

表单验证类

<?php
/**
 * 表单验证类
 */
class FormValidator {
    private $errors = [];
    private $data = [];
    public function __construct($data = []) {
        $this->data = $data;
    }
    /**
     * 验证必填字段
     */
    public function required($field, $label = '') {
        if (empty($this->data[$field])) {
            $this->errors[$field][] = $label . '不能为空';
        }
        return $this;
    }
    /**
     * 验证邮箱
     */
    public function email($field, $label = '') {
        if (isset($this->data[$field]) && !filter_var($this->data[$field], FILTER_VALIDATE_EMAIL)) {
            $this->errors[$field][] = $label . '格式不正确';
        }
        return $this;
    }
    /**
     * 验证手机号
     */
    public function phone($field, $label = '') {
        if (isset($this->data[$field]) && !preg_match('/^1[3-9]\d{9}$/', $this->data[$field])) {
            $this->errors[$field][] = $label . '格式不正确';
        }
        return $this;
    }
    /**
     * 验证长度
     */
    public function length($field, $min = 0, $max = 255, $label = '') {
        if (isset($this->data[$field])) {
            $length = mb_strlen($this->data[$field]);
            if ($length < $min || $length > $max) {
                $this->errors[$field][] = $label . "长度必须在{$min}-{$max}之间";
            }
        }
        return $this;
    }
    /**
     * 验证数字范围
     */
    public function numberRange($field, $min, $max, $label = '') {
        if (isset($this->data[$field])) {
            $value = (int)$this->data[$field];
            if ($value < $min || $value > $max) {
                $this->errors[$field][] = $label . "必须在{$min}-{$max}之间";
            }
        }
        return $this;
    }
    /**
     * 验证正则
     */
    public function pattern($field, $pattern, $label = '', $message = '') {
        if (isset($this->data[$field]) && !preg_match($pattern, $this->data[$field])) {
            $this->errors[$field][] = $message ?: $label . '格式不正确';
        }
        return $this;
    }
    /**
     * 验证是否为日期
     */
    public function date($field, $format = 'Y-m-d', $label = '') {
        if (isset($this->data[$field])) {
            $d = DateTime::createFromFormat($format, $this->data[$field]);
            if (!$d || $d->format($format) !== $this->data[$field]) {
                $this->errors[$field][] = $label . '日期格式不正确';
            }
        }
        return $this;
    }
    /**
     * 自定义验证
     */
    public function custom($field, $callback, $label = '', $message = '') {
        if (isset($this->data[$field]) && !$callback($this->data[$field])) {
            $this->errors[$field][] = $message ?: $label . '验证失败';
        }
        return $this;
    }
    /**
     * 验证是否通过
     */
    public function passes() {
        return empty($this->errors);
    }
    /**
     * 获取错误信息
     */
    public function getErrors() {
        return $this->errors;
    }
    /**
     * 获取第一个错误信息
     */
    public function getFirstError() {
        if (!empty($this->errors)) {
            foreach ($this->errors as $errors) {
                return $errors[0];
            }
        }
        return null;
    }
    /**
     * 清理验证数据
     */
    public function cleanData() {
        $cleanData = [];
        foreach ($this->data as $key => $value) {
            $cleanData[$key] = $this->cleanInput($value);
        }
        return $cleanData;
    }
    /**
     * 清理输入
     */
    private function cleanInput($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

使用示例

<?php
// 初始化安全中心
require_once 'SecurityCenter.php';
require_once 'FormValidator.php';
$security = SecurityCenter::getInstance();
$security->run();
// 获取CSRF Token
$csrfToken = $security->generateCSRFToken();
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 验证表单数据
    $validator = new FormValidator($_POST);
    $validator
        ->required('username', '用户名')
        ->length('username', 3, 20, '用户名')
        ->required('email', '邮箱')
        ->email('email', '邮箱')
        ->required('phone', '手机号')
        ->phone('phone', '手机号')
        ->required('password', '密码')
        ->length('password', 8, 20, '密码');
    // 密码强度验证
    if (isset($_POST['password']) && 
        !$security->validatePasswordStrength($_POST['password'])) {
        $validator->custom('password', function($v) { 
            return $security->validatePasswordStrength($v); 
        }, '密码', '密码强度不够');
    }
    if (!$validator->passes()) {
        $errors = $validator->getErrors();
        // 处理错误
    } else {
        // 处理文件上传
        if (isset($_FILES['file'])) {
            $uploadResult = $security->validateFileUpload($_FILES['file']);
            if ($uploadResult !== true) {
                // 处理上传错误
            }
        }
        $cleanData = $validator->cleanData();
        // 数据加密示例
        $encryptedData = $security->encryptData($cleanData['password'], 'secret_key');
        // 保存数据到数据库
        // ...
    }
}
// 输出CSRF令牌到表单
?>
<form method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
    <!-- 表单字段 -->
</form>

数据库安全类

<?php
/**
 * 数据库安全封装
 */
class DatabaseSecurity {
    private $pdo;
    public function __construct($host, $dbname, $username, $password) {
        try {
            $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
            $this->pdo = new PDO($dsn, $username, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
        } catch (PDOException $e) {
            die('数据库连接失败');
        }
    }
    /**
     * 安全查询方法
     */
    public function safeQuery($sql, $params = []) {
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (PDOException $e) {
            SecurityCenter::getInstance()->logSecurityEvent('database_error', 
                $_SERVER['REMOTE_ADDR'], $e->getMessage());
            return false;
        }
    }
    /**
     * 获取单行数据
     */
    public function fetchOne($sql, $params = []) {
        $stmt = $this->safeQuery($sql, $params);
        return $stmt ? $stmt->fetch() : false;
    }
    /**
     * 获取多行数据
     */
    public function fetchAll($sql, $params = []) {
        $stmt = $this->safeQuery($sql, $params);
        return $stmt ? $stmt->fetchAll() : [];
    }
    /**
     * 安全插入
     */
    public function safeInsert($table, $data) {
        $fields = array_keys($data);
        $placeholders = array_map(function($field) {
            return ':' . $field;
        }, $fields);
        $sql = "INSERT INTO $table (" . implode(', ', $fields) . ") 
                VALUES (" . implode(', ', $placeholders) . ")";
        return $this->safeQuery($sql, $data);
    }
    /**
     * 安全更新
     */
    public function safeUpdate($table, $data, $where) {
        $fields = array_keys($data);
        $sets = array_map(function($field) {
            return "$field = :$field";
        }, $fields);
        $sql = "UPDATE $table SET " . implode(', ', $sets) . " WHERE $where";
        return $this->safeQuery($sql, $data);
    }
    /**
     * 安全删除
     */
    public function safeDelete($table, $id) {
        $sql = "DELETE FROM $table WHERE id = :id";
        return $this->safeQuery($sql, ['id' => (int)$id]);
    }
    /**
     * 获取最后插入ID
     */
    public function lastInsertId() {
        return $this->pdo->lastInsertId();
    }
    /**
     * 事务处理
     */
    public function transaction($callback) {
        try {
            $this->pdo->beginTransaction();
            $result = $callback($this);
            $this->pdo->commit();
            return $result;
        } catch (Exception $e) {
            $this->pdo->rollBack();
            SecurityCenter::getInstance()->logSecurityEvent('transaction_error', 
                $_SERVER['REMOTE_ADDR'], $e->getMessage());
            return false;
        }
    }
}

安全配置文件

<?php
// config/security.php
return [
    'enable_html_filter' => true,
    'enable_sql_filter' => true,
    'enable_xss_filter' => true,
    'enable_csrf_filter' => true,
    'enable_sql_injection_protection' => true,
    'enable_file_upload_protection' => true,
    // 访问控制
    'max_attempts' => 5,
    'lockout_time' => 900,
    'session_timeout' => 1800,
    // IP白名单/黑名单
    'whitelist_ips' => ['127.0.0.1'],  // 只能访问的IP
    'blacklist_ips' => ['192.168.1.100'],   // 禁止访问的IP
    // 文件上传安全
    'allowed_extensions' => ['jpg', 'jpeg', 'png', 'gif', 'pdf'],
    'max_file_size' => 5 * 1024 * 1024, // 5MB
    // 日志
    'log_security_events' => true,
    // 数据加密
    'encryption_key' => 'your_secure_encryption_key_here'
];

安全监控脚本

<?php
/**
 * 安全监控和告警脚本
 */
class SecurityMonitor {
    private $security;
    private $alertEmail;
    public function __construct($alertEmail = 'admin@example.com') {
        $this->security = SecurityCenter::getInstance();
        $this->alertEmail = $alertEmail;
    }
    /**
     * 运行安全扫描
     */
    public function runScan() {
        $this->scanLogs();
        $this->scanFiles();
        $this->checkSystemIntegrity();
        $this->checkForMalware();
    }
    /**
     * 扫描安全日志
     */
    private function scanLogs() {
        $logDir = __DIR__ . '/../logs/security/';
        $files = glob($logDir . '*.log');
        foreach ($files as $file) {
            $content = file_get_contents($file);
            // 检测异常行为
            if (preg_match('/Type: (sql_injection|xss_attack|csrf_attack)/', $content)) {
                $this->sendAlert('检测到安全攻击', $file);
            }
            // 检测暴破尝试
            if (substr_count($content, 'Type: login_attempt') > 10) {
                $this->sendAlert('可能正在受到暴力破解攻击', $file);
            }
        }
    }
    /**
     * 扫描文件完整性
     */
    private function scanFiles() {
        $webRoot = $_SERVER['DOCUMENT_ROOT'];
        $hashFile = __DIR__ . '/../logs/file_hashes.json';
        if (file_exists($hashFile)) {
            $hashes = json_decode(file_get_contents($hashFile), true);
            // 扫描关键文件
            $criticalFiles = ['index.php', 'config.php', 'security.php'];
            foreach ($criticalFiles as $file) {
                $path = $webRoot . '/' . $file;
                if (file_exists($path)) {
                    $hash = md5_file($path);
                    if (isset($hashes[$file]) && $hashes[$file] !== $hash) {
                        $this->sendAlert('关键文件被修改', $file);
                    }
                }
            }
        }
    }
    /**
     * 检查系统完整性
     */
    private function checkSystemIntegrity() {
        // 检查会话目录
        $sessionDir = ini_get('session.save_path');
        if (!is_writable($sessionDir)) {
            $this->sendAlert('会话目录不可写', $sessionDir);
        }
        // 检查临时目录
        $tmpDir = sys_get_temp_dir();
        if (!is_writable($tmpDir)) {
            $this->sendAlert('临时目录不可写', $tmpDir);
        }
    }
    /**
     * 检查恶意软件
     */
    private function checkForMalware() {
        $malwarePatterns = [
            '/base64_decode\s*\(/i',
            '/eval\s*\(/i',
            '/shell_exec/i',
            '/passthru/i',
            '/system\s*\(/i',
            '/exec\s*\(/i',
            '/create_function/i',
            '/assert\s*\(/i'
        ];
        // 扫描PHP文件
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT'])
        );
        foreach ($files as $file) {
            if ($file->getExtension() == 'php') {
                $content = file_get_contents($file->getPathname());
                foreach ($malwarePatterns as $pattern) {
                    if (preg_match($pattern, $content)) {
                        $this->sendAlert('发现可疑代码', $file->getPathname());
                        break;
                    }
                }
            }
        }
    }
    /**
     * 发送告警邮件
     */
    private function sendAlert($subject, $detail) {
        $message = "安全告警详情:\n";
        $message .= "时间: " . date('Y-m-d H:i:s') . "\n";
        $message .= "详情: $detail\n";
        $message .= "IP: " . $_SERVER['ADDR'] . "\n";
        mail($this->alertEmail, $subject, $message);
    }
}

这个PHP安全中心提供了以下核心功能:

  1. 多重防护机制:SQL注入、XSS、CSRF防护
  2. 访问控制:IP白名单/黑名单、请求频率限制
  3. 会话安全:会话超时、会话固定攻击防护
  4. 文件上传安全:类型检查、大小限制、MIME验证
  5. 数据加密:AES-256加密解密
  6. 安全事件日志:记录所有安全相关事件
  7. 实时监控和告警:文件完整性检查、恶意代码检测

可以根据具体需求调整配置和使用场景。

抱歉,评论功能暂时关闭!