萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 安全過濾與轉義工具類:防 XSS、SQL 注入、目錄遍歷

核心原則

  • 輸入過濾、輸出轉義:根據上下文(HTML、SQL、Shell、URL)選擇對應函數
  • 白名單優於黑名單
  • 使用成熟庫:如 `HTMLPurifier`、PDO 預處理,勿自造輪子

常用轉義函數封裝

<?php
class Security
{
    // HTML 輸出轉義(雙引號、單引號、<、>、&)
    public static function h(string $str, int $flags = ENT_QUOTES | ENT_SUBSTITUTE, string $encoding = 'UTF-8'): string
    {
        return htmlspecialchars($str, $flags, $encoding);
    }

    // HTML 內容淨化(允許安全標籤)
    public static function purify(string $html): string
    {
        require_once 'HTMLPurifier.auto.php';
        $config = HTMLPurifier_Config::createDefault();
        $config->set('HTML.Allowed', 'p,b,i,u,em,strong,a[href|title],ul,ol,li,br,img[src|alt|width|height]');
        return (new HTMLPurifier($config))->purify($html);
    }

    // SQL 識別符轉義(表名、欄位名)
    public static function escapeIdent(string $ident): string
    {
        return '`' . str_replace('`', '``', $ident) . '`';
    }

    // Shell 參數轉義
    public static function shArg(string $arg): string
    {
        return escapeshellarg($arg);
    }

    // 路徑安全:防止目錄遍歷
    public static function safePath(string $baseDir, string $userInput): ?string
    {
        $base = realpath($baseDir);
        $target = realpath($baseDir . DIRECTORY_SEPARATOR . $userInput);
        if ($target && strpos($target, $base) === 0) {
            return $target;
        }
        return null;
    }

    // 通用陣列遞迴轉義
    public static function recursive(callable $fn, array &$arr): void
    {
        array_walk_recursive($arr, function (&$v) use ($fn) { $v = $fn($v); });
    }
}
?>

資料庫層最佳實踐

<?php
// PDO 預處理(首選)
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status = ?');
$stmt->execute([$email, 1]);

// 如必須手動拼接(不推薦)
$safeEmail = $pdo->quote($email); // 含引號
$sql = "SELECT * FROM users WHERE email = $safeEmail";
?>

上傳檔案安全

  1. 驗證 MIME:`finfo_file($finfo, $tmp, FILEINFO_MIME_TYPE)`
  2. 重命名儲存:`$newName = bin2hex(random_bytes(16)) . '.webp'`
  3. 存放於 Web 根目錄外,或配置 Nginx `location ~ \.php$ { deny all; }`
  4. 圖片二次渲染:`imagecreatefromstring(file_get_contents($tmp))` → `imagewebp()` 移除潛在惡意代碼

HTTP 安全頭部

<?php
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-$nonce'; style-src 'self'; img-src 'self' data:;");
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");
header("Permissions-Policy: geolocation=(), microphone=()");
?>
copyright © 萬盛學電腦網 all rights reserved