萬盛學電腦網

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

PHP 錯誤處理最佳實踐:關閉顯示、記錄日誌、資安加固

為何要關閉錯誤顯示?

  • 防止敏感資訊洩露 (路徑、資料庫結構、堆疊追蹤)
  • 避免干擾正常輸出 (JSON API、圖片、下載)
  • 符合資安合規 (PCI-DSS、GDPR 等)

php.ini 核心設定

; ────────────────────────────────────────
; 生產環境必備設定
; ────────────────────────────────────────
display_errors = Off           ; 瀏覽器不顯示錯誤
display_startup_errors = Off   ; 啟動階段錯誤也不顯示
log_errors = On                ; 寫入錯誤日誌
error_log = /var/log/php/error.log  ; 專屬日誌檔 (需可寫)

; 錯誤報告層級:生產建議
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE
; 開發環境可用 E_ALL

; 記錄格式加入時間戳 (PHP 8.0+)
; error_log = syslog 亦可導向系統日誌

程式碼層面控制

<?php
// 入口檔最早處設定 (若無法改 php.ini)
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/logs/php_error.log');
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);

// 自訂錯誤處理器 (記錄更豐富資訊)
set_error_handler(function (int $code, string $msg, string $file, int $line) {
    $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
    $log = sprintf(
        "[%s] %s in %s:%d\nStack:\n%s\n---\n",
        date('c'),
        $msg,
        $file, $line,
        json_encode($trace, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
    );
    error_log($log, 3, ini_get('error_log'));
    // 開發環境可選擇性顯示
    if (ini_get('display_errors')) {
        echo "
$log
"; } return true; // 不執行內建處理器 }); // 例外處理器 set_exception_handler(function (Throwable $e) { $code = $e->getCode() ?: 500; http_response_code($code); // 記錄 error_log($e->getMessage() . "\n" . $e->getTraceAsString()); // 使用者友善頁面 if (ini_get('display_errors')) { echo "

系統錯誤

" . htmlspecialchars($e->getMessage()) . "
"; } else { echo "

服務暫時不可用,請稍後再試

"; } }); // 致命錯誤捕獲 (PHP 7+) register_shutdown_function(function () { $error = error_get_last(); if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) { // 交給 exception handler 處理 (new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])) ->setExceptionHandler(); } }); ?>

日誌輪轉與監控

# /etc/logrotate.d/php
/var/log/php/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
    postrotate
        systemctl reload php-fpm > /dev/null 2>&1 || true
    endscript
}

資安加固清單

項目設定風險
expose_phpOff隱藏 X-Powered-By 標頭
disable_functionsexec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,pcntl_exec防命令注入
open_basedir/var/www/:/tmp/:/var/lib/php/sessions/限制檔案存取範圍
allow_url_fopenOff防 RFI (遠程檔案包含)
allow_url_includeOff防 RFI
session.cookie_httponly1防 JS 竊取 Session
session.cookie_secure1 (HTTPS)僅 HTTPS 傳輸 Cookie
copyright © 萬盛學電腦網 all rights reserved