PHP防篡改保护机制

```html PHP防篡改保护机制:保障核心文件与数据完整性

PHP防篡改保护机制

在Web应用安全中,防止关键文件(如配置、核心类库)被恶意篡改是基础防线。PHP虽无内置“防篡改”模块,但可通过文件完整性校验 + 运行时防护构建可靠保护机制。

1. 基于哈希的文件完整性校验

对敏感文件(如 config.phpdatabase.php)生成并验证SHA-256指纹:

<?php
// integrity_check.php —— 部署后首次运行生成签名
$protectedFiles = [
    __DIR__ . '/config.php',
    __DIR__ . '/core/Router.php',
];

$signatures = [];
foreach ($protectedFiles as $file) {
    if (file_exists($file)) {
        $hash = hash_file('sha256', $file);
        $signatures[basename($file)] = $hash;
    }
}
file_put_contents(__DIR__ . '/.integrity.sign', json_encode($signatures, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
echo "✅ 签名已生成:.integrity.sign\n";
?>

每次请求前校验(建议放入入口文件 index.php):

<?php
// 入口处校验(生产环境启用)
if (file_exists(__DIR__ . '/.integrity.sign')) {
    $signatures = json_decode(file_get_contents(__DIR__ . '/.integrity.sign'), true);
    foreach ($signatures as $filename => $expectedHash) {
        $path = __DIR__ . '/' . $filename;
        if (file_exists($path) && hash_file('sha256', $path) !== $expectedHash) {
            error_log("[SECURITY] 文件篡改检测:{$filename}");
            http_response_code(500);
            die("系统文件完整性校验失败,请联系管理员。");
        }
    }
}
?>

2. 运行时配置锁定(防动态修改)

禁止通过 ini_set()putenv() 修改关键配置:

<?php
// 在 bootstrap.php 中禁用危险函数(需配合 php.ini)
if (function_exists('disable_functions')) {
    // 实际需在 php.ini 中设置:disable_functions = ini_set,putenv,shell_exec,exec
}
// 或运行时重定义(仅限开发测试)
if (PHP_SAPI !== 'cli') {
    function ini_set($var, $val) {
        throw new RuntimeException("禁止运行时修改配置:{$var}");
    }
}
?>

3. 关键常量只读化

使用 define() 定义不可变常量,并禁用后续覆盖:

<?php
// config.php
define('APP_ENV', 'production');
define('DB_HOST', 'localhost');

// 防止被 define() 覆盖(PHP 7.4+ 支持 readonly)
if (version_compare(PHP_VERSION, '7.4.0', '>=')) {
    // 可结合 opcache.preload 提升安全性
}
?>
⚠️ 重要提醒:防篡改≠绝对安全。必须配合:
• 严格的文件系统权限(如 chown www-data:www-data + chmod 644
• Web服务器禁用脚本执行目录(如 Nginx 中 location ~ \.php$ { deny all; }
• 定期扫描(如使用 ssh-audit 或自定义脚本)

防篡改不是一劳永逸,而是持续验证的过程。将哈希校验融入CI/CD流程,结合日志审计与实时告警,才能真正筑牢PHP应用的第一道安全屏障。

```