Databases Reference
In-Depth Information
Handling errors in production code
Production code needs to handle errors gracefully. As mentioned earlier, it's very useful
to allow PHP error messages to be displayed while you're developing and debugging
your code. However, when you're ready to deploy your application, we recommend
that you customize the messages that are displayed so that they're more polite and also
give away fewer details about your system to potential attackers.
We can have our showerror( ) function simply display a generic message as follows:
// Custom error handler function
function showerror($connection)
{
// Display a message to the user
echo "<h3>Failure</h3>
Unfortunately we're having technical difficulties.
Please try again later.";
}
However, as the administrator, you won't know anything about the error unless your
users complain.
You can configure PHP to record errors to a logfile. To do this, you'll need to edit the
php.ini configuration file and enable the log_errors option:
log_errors = On
You should also specify the location of the logfile with the error_log option. The web
server should be able to write to this file, so you should check the permission settings
of the directory you use. For example, we can specify the file /tmp/php_errors.log for a
Linux or Mac OS X system:
error_log = /tmp/php_errors.log
On a Windows system, use a path such as C:\php_errors.log . If you modify the PHP
configuration, you will need to restart the web server to activate the changes.
You can also log errors using the PHP error_log( ) function; let's modify our
showerror( ) function to log errors:
// Custom error handler function
function showerror($connection)
{
// Display a message to the user
echo "<h3>Failure</h3>
Unfortunately we're having technical difficulties; this has been logged.
Please try again later.";
// Create message with the current timestamp and the MySQL error.
$sMessage= date("Y.m.d_H:i:s").": ".mysqli_error($connection)."\n";
// Log the timestamp and error description to the file /tmp/php_errors.log
error_log(
$sMessage,
3,
 
Search WWH ::




Custom Search