直接訪問主題檔案 (如 `wp-content/themes/twentytwelve/index.php`) 會觸發 `Call to undefined function get_header()` 致命錯誤,若 `display_errors=On` 會洩露絕對路徑、資料庫前綴、插件結構等敏感資訊。
; php.ini (生產環境必須) display_errors = Off display_startup_errors = Off log_errors = On error_log = /var/log/php_errors.log error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
# Nginx fastcgi_param PHP_VALUE "display_errors=off"; # Apache .htaccess php_flag display_errors off
在主題 `index.php`、 `page.php` 等入口檔**最頂端**添加:
<?php
// 1. 關閉錯誤顯示
ini_set('display_errors', 0);
// 2. 核心函數存在性檢查,不存在則重定向首頁
if (!function_exists('get_header')) {
$home = home_url('/');
header("Location: $home", true, 302);
exit;
}
// 3. 正常載入主題
get_header();
?>
<?php
// wp-config.php 或 mu-plugin
function custom_error_handler(int $errno, string $errstr, string $errfile, int $errline): bool
{
// 記錄日誌
error_log("[$errno] $errstr in $errfile:$errline");
// 生產環境不顯示細節
if (defined('WP_DEBUG') && WP_DEBUG) return false; // 交給預設處理
// 致命錯誤顯示友好頁面
if (in_array($errno, [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
status_header(500);
nocache_headers();
echo '服務暫時不可用 系統維護中,請稍後再試
';
exit;
}
return true;
}
set_error_handler('custom_error_handler');
register_shutdown_function(function () {
$err = error_get_last();
if ($err && in_array($err['type'], [E_ERROR, E_PARSE])) {
custom_error_handler($err['type'], $err['message'], $err['file'], $err['line']);
}
});
?>