Understanding the Issue:
In your provided code, you attempt to connect to a database using mysqli_connect and print a custom error message in case the connection fails. However, PHP 8.1 and later handle errors differently, raising exceptions instead of requiring manual handling.
Hidden Custom Error Message:
Starting in PHP 8.1, mysqli_connect generates an exception when an error occurs, meaning your code no longer needs to manually check for the connection status. Additionally, you should avoid displaying custom error messages to users. Instead, use PHP's error handling mechanisms or provide a generic error page.
Display Errors Configuration:
To prevent PHP from displaying error messages to users, set the 'display_errors' option in php.ini or your code to 0:
ini_set('display_errors', 0);
Error Handler for Site Users:
For a user-friendly error page, use an error handler that logs the error, sets an HTTP 500 status code, and displays a generic error message or redirects to an error page.
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> An internal server error has been occurred.<br> Please try again later."; } });
Handling Connection Errors Separately:
If you want to handle connection errors specifically, such as testing user credentials, use try..catch blocks in a dedicated connection test code:
try { $conn = mysqli_connect(...); } catch (mysqli_sql_exception $e) { // Handle connection error }
Hiding Connection Credentials:
PHP 8.2 onwards hides the database password from stack traces for improved security.
The above is the detailed content of Why Aren\'t My Custom MySQLi Connection Error Messages Displaying in PHP 8.1 ?. For more information, please follow other related articles on the PHP Chinese website!