Problem:
Finding best practice for error handling using PDO. The options I have found on websites, SO, books, etc.
- A great number of websites say you should echo your error messages in your
catch
block. - A large number of users on SO say that you should never echo error messages due to security risks.
- Others are recommending logging it to a log file outside the document root.
- Some use error handling to log it to a SQL table.
With a multitude of options, it gets quite easy to drown into what option you should be using. Of course you could use a MVC framework and let it handle error logging for you, but how would it look like if you are not using MVC.
As I have understood it error handling should like the following in development environment:
display_errors = On
display_startup_errors = On
error_reporting = -1
log_errors = On
Or if no access is available to the php.ini file:
error_reporting(-1);
ini_set("display_errors", 1);
And in production environment:
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On
Or if no access is available to the php.ini file:
error_reporting(0);
To take an example of a database connection in production environment.
Code:
<?php
// Error handling
error_reporting(0);
// Get credentials from outside document root
require_once('../settings.php');
// Tests connection to database
try {
$dbh = new PDO(
sprintf(
'mysql:host=%s;dbname=%s;port=%s;charset=%s',
$settings['host'],
$settings['name'],
$settings['port'],
$settings['charset']
),
$settings['username'],
$settings['password']
);
// Prevents emulated prepares and activates error handling
// PDO::ERRMODE_EXCEPTION
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
// Catches errors raised by PDO
catch (PDOException $e) {
// Prints error messages to file
file_put_contents('/home/ubuntu/errors.log', 'Error: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
// Shows generic error message to user
header('Location: 404.php');
exit;
}
?>
Question:
- What is the best practice for handling errors in general in PHP?
- What is the best practice for handling errors in the catch-block?