Security Fundamentals

Secure Error Handling and Logging in PHP

Record useful diagnostic events without exposing stack traces, credentials, tokens, or internal details to visitors.

Keep production errors out of responses

Configure production PHP to log errors rather than display them:

display_errors = Off
log_errors = On

Return a generic message and an appropriate HTTP status to the visitor.

Log useful context

try {
    // Perform an application operation.
} catch (Throwable $exception) {
    error_log(sprintf(
        'Operation failed; request_id=%s; type=%s',
        $requestId,
        get_class($exception)
    ));

    http_response_code(500);
    echo 'An unexpected error occurred.';
}

Never log secrets

Avoid recording passwords, session IDs, access tokens, full payment details, or unnecessary personal data. Sanitize user-controlled values to prevent log injection.

Protect log storage

Keep logs outside the public web root, restrict filesystem permissions, rotate old files, and define retention periods. Do not reveal SQL statements, paths, or stack traces in public responses.