In an attempt to establish a database connection, you encountered an issue where the custom error message you defined was not being displayed when the connection failed. You are also seeking a method to suppress error messages from the user's view.
Starting with PHP 8.1, the mysqli extension now automatically throws exceptions in the event of an error, eliminating the need for manual error handling as was done in earlier versions of PHP.
Custom error messages, like the one you defined, are no longer recommended for error handling. Both PDO and mysqli have the ability to raise errors automatically, just like any other PHP command. Therefore, manually checking for errors, as you attempted to do with the if (!$conn) segment, is obsolete.
To prevent error messages from reaching the user, you should utilize the display_errors configuration option, which can be set to 0 to suppress all error output. This can be configured in the php.ini file or directly in your PHP code:
ini_set('display_errors', 0);
Instead of displaying cryptic error messages, it is advisable to present a user-friendly error page to site visitors. This can be achieved by setting up an error handler, such as the one below, which will catch all irrecoverable errors:
set_exception_handler(function ($e)
{
error_log($e);
http_response_code(500);
if (ini_get('display_errors')) {
echo $e;
} else {
echo "<h1>500 Internal Server Error</h1>\nAn internal server error has been occurred.<br>\nPlease try again later.";
}
});
If you need to specifically handle database connection errors, you can use a separate connection test script wrapped in a try-catch block, separate from your regular connection code.
For enhanced security, update your PHP version to 8.2 or later, which obscures database passwords from appearing in the stack trace.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3