PHP - Fix Lỗi Khi Tắt display_errors


Thủ Thuật 18 lượt xem 0 bình luận

Chúng ta thường tắt display_errors để tránh lộ các thông tin nhạy cảm, ví dụ như cấu trúc thư mục, tên file, và code logic, tuy nhiên điều này đồng nghĩa với việc trang sẽ chỉ hiển thị lỗi 500 nếu code dính bug. Sau đây là cách khắc phục, ở đây mình sử dụng set_exception_handler (ngoại trừ xử lý) để tùy chỉnh lỗi 500 cho nó được nhìn theo hướng thiện cảm hơn.

ini_set('display_errors', 0); 
ini_set('display_startup_errors', 1);
error_reporting(-1);

// Custom error handler
set_error_handler('customErrorHandler');
set_exception_handler('customExceptionHandler');
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    // If display_errors is off, output a generic system error message
    if (!ini_get('display_errors')) {
        header('HTTP/1.1 500 Internal Server Error');
        echo "System error: [$errno] $errstr in $errfile on line $errline";
        exit();
    }
    return false; // Allow the PHP internal error handler to run as well
}
function customExceptionHandler($exception) {
    $message = $exception->getMessage();
    $line = $exception->getLine();
    $trace = $exception->getTrace();

    $function = isset($trace[0]['function']) ? $trace[0]['function'] : '(unknown function)';
    $class = isset($trace[0]['class']) ? $trace[0]['class'] : '(unknown class)';
    // If display_errors is off, output a generic system error message
    if (!ini_get('display_errors')) {
        header('HTTP/1.1 500 Internal Server Error');
        echo 'System error: <b>' . htmlspecialchars($message) . '</b> on line <b>' . htmlspecialchars($line) . '</b> in function <b>' . htmlspecialchars($function) . '</b> of class <b>' . htmlspecialchars($class) . '</b>';
        exit();
    }
    return false; // Allow the PHP internal exception handler to run as well
}

Nguồn: Asuna - Dorew.Ovh


  • Tác giả: Đặng Minh Đông
  • Liên kết: https://dangminhdong.name.vn/thu-thuat/17.html
  • Bản quyền: Mọi thắc mắc về bản quyền, hãy để lại bình luận.
  • Sửa lần cuối: 16-02-2025
    Bình luận ( 0 )
    OωO
    Riêng tư