Catching at source

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password.
PDO Connections and Connection management

Ideally you shouldn’t be displaying any error messages to the outside world at all – especially on a production server. Even during development you should probably limit debugging output to approved IP addresses only.

You can take a very simple step to avoid displaying your username and password should the connection fail and you (or somebody else) forget to catch the error. By subclassing the PDO database abstraction layer you can make sure that you implicitly catch the exception message by temporarily changing the PHP exception handler.

You could generate your own backtrace here as well and sanitize the data to remove any passwords before display but I shall leave that as an exercise for the reader.

All you need to do now is remember to use the SafePDO class instead of instantiating a standard PDO object.

[sourcecode language=’php’]< ?php Class SafePDO extends PDO { public static function exception_handler($exception) { // Output the exception details die('Uncaught exception: ', $exception->getMessage());
}

public function __construct($dsn, $username=”, $password=”, $driver_options=array()) {

// Temporarily change the PHP exception handler while we . . .
set_exception_handler(array(__CLASS__, ‘exception_handler’));

// . . . create a PDO object
parent::__construct($dsn, $username, $password, $driver_options);

// Change the exception handler back to whatever it was before
restore_exception_handler();
}

}

try {

// Connect to the database with defined constants
$dbh = new SafePDO(PDO_DSN, PDO_USER, PDO_PASSWORD);

// The rest of your code goes here . . .

// Destroy the database connection
$dbh = null;

} catch (Exception $e) {
SafePDO::exception_handler($e);
}

?>[/sourcecode]