Some Error Handling in PHP | At the time of making a web application, error handling is very important. Standard error handling in PHP is very simple. Error sent to the browser shows an error message, the file name, how many lines of code to the scene of the error. Without a good error handling, of course, in the event of an error, the error will appear in the browser and viewed by all users. This could pose a threat to the security of the website. PHP has provided a function for error handling function as described in Error Handling and Logging.
Function die ([string $message]) serves to stop the execution of the next line of code and gives output optional parameter $message. Example:
<?phpno error handling such as php code above, at the time could not connect to the mysql database, it will display an error message like this:
//without error handling
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("test");
$result = mysql_query("select * from table_name");
while($row = mysql_fetch_array($result)){
echo $row['field_name'];
}
?>
mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/run/mysql/mysql.sock' (2) in /home/ellyxc/public_html/tutorial/error/die.php on line 3of course users will be puzzled to see the above error, the function die(), can be minimized error message such as:
Warning: mysql_select_db() [function.mysql-select-db]: Can't connect to local MySQL server through socket '/var/run/mysql/mysql.sock' (2) in /home/ellyxc/public_html/tutorial/error/die.php on line 4
Warning: mysql_select_db() [function.mysql-select-db]: A link to the server could not be established in /home/ellyxc/public_html/tutorial/error/die.php on line 4
Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysql/mysql.sock' (2) in /home/ellyxc/public_html/tutorial/error/die.php on line 5
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/ellyxc/public_html/tutorial/error/die.php on line 5
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/ellyxc/public_html/tutorial/error/die.php on line 6
<?phpat the time could not connect to the database, the code above will give output like this
//with error handling
$connection = mysql_connect("localhost", "user", "password")
or die('Could not connect to database');
mysql_select_db("test");
$result = mysql_query("select * from table_name");
while($row = mysql_fetch_array($result)){
echo $row['field_name'];
}
?>
Could not pass up a connection to the database
2. Setting Error Reporting Level
PHP provides the ability to determine what error error displayed using the function error_reporting ([int $level]). Parameter $level could be filled with the following values:
Value | Constant | Description |
---|---|---|
1 | E_ERROR | Fatal run-time errors. Errors that can not be your game, such as a memory allocation problem. Script execution stops. |
2 | E_WARNING | Run-time warnings (non-fatal errors). Script Execution does not stop. |
4 | E_PARSE | Compile-time parse errors. The error occurred because of a typing error in php code. |
8 | E_NOTICE | Run-time notices. Error indicating that the script can cause another error. |
256 | E_USER_ERROR | The error message generated by the user. As E_ERROR, but generated using trigger_error() function . |
512 | E_USER_WARNING | The error message generated by the user. As E_WARNING, but generated using trigger_error() function. |
1024 | E_USER_NOTICE | The error message generated by the user. As E_NOTICE, but generated using trigger_error() function. |
2048 | E_STRICT | Errors give suggestions changes to your code to ensure the best interoperability and compatibility of your php code. |
30719 | E_ALL | All exceptions except E_STRICT. |
more tables can be found at http://www.php.net/manual/en/errorfunc.constants.php. Examples of using error_reporting().
<?php
//all exceptions
error_reporting(E_ALL);
//all exceptions including E_STRICT
error_reporting(E_ALL|E_STRICT);
//does not display an error
error_reporting(0);
?>
3. Not Display Error
From the error display which is not understood by the user, sometimes it is better not to show error at all, but merely noted the error occurred in a file. For it can use the code below.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
ini_set('error_log', 'logs/error.log');
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("test");
$result = mysql_query("select * from table_name");
while($row = mysql_fetch_array($result)){
echo $row['field_name'];
}
?>
To not show error used function ini_set ('display_errors', 'Off'); (3rd row). In row 5 to store the error that occurred in the file "logs/error.log". In the event of an error, the file "logs/error.log" will contain data like this
[21-Dec-2016 11:57:56] PHP Warning: mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Can't connect to local MySQL server through socket '/var/run/mysql/mysql.sock' (2) in /home/ellyxc/public_html/tutorial/error/die.php on line 6
[21-Dec-2016 11:57:56] PHP Stack trace:
[21-Dec-2016 11:57:56] PHP 1. {main}() /home/ellyxc/public_html/tutorial/error/die.php:0
[21-Dec-2016 11:57:56] PHP 2. mysql_connect() /home/ellyxc/public_html/tutorial/error/die.php:6
Taking the option to not display the error could be confusing to the user. A better way is to take the user to a specific page, to notify the user that was an error.
4. Creating a Custom Error Handler
In addition to providing the standard error handling, PHP also provides the ability to create a function that is tasked to handle the error that occurs is called the Custom Error Handler. A Custom Error Handler has a format like this
error_funciton($error_level,$error_message, $error_file,$error_line,$error_context)
Parameter | Description |
---|---|
error_level | level error |
error_message | Error message occurs |
error_file | Optional. The file name where the error occurred |
error_line | Optional. Number of lines of code where the error occurred |
error_context | Optional. An array containing all the variables and valuenya that caused the error |
example:
<?php
function customError($errorLevel,$errorMsg){
@session_start();
$_SESSION['error_msg'] = $errorMsg;
header("Location: error.php");
exit;
}
set_error_handler("customError");
error_reporting(E_ALL);
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("test");
$result = mysql_query("select * from table_name");
while($row = mysql_fetch_array($result)){
echo $row['field_name'];
}
?>
Rows 2-7 are examples of Custom Error Handler, an error message is stored into a session, and the user is taken to a page "error.php" in the event of error. In line 8 used function set_error_handler ($handler); to determine Custom Error Handler used in the event of error. Parameter $handler is filled with string function name Custom Error Handler. File "error.php" could be as follows.
<?php
session_start();
?>
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Error</h1>
<p>Sorry we can not process your request.</p>
<p>Error messages: <?php echo $_SESSION['error_msg'];?></p>
</body>
</html>
5. Triggering Error
PHP provides the ability to generate custom error message using trigger_error() function. This function can be used for example when the user enters a character illegal characters, such as inserting a html tag. Example:
Using trigger_error with Custom Error Handler$input = "<strong>bold letters</strong>";
if(preg_match('/<(.+)>/', $input)){
trigger_error("You may not enter html tags");
}
function customError($errorLevel,$errorMsg){
@session_start();
$_SESSION['error_msg'] = $errorMsg;
header("Location: error.php");
exit;
}
set_error_handler("customError", E_USER_WARNING);
$input = "<strong>bold letters</strong>";
if(preg_match('/<(.+)>/', $input)){
trigger_error("You may not enter html tags", E_USER_WARNING);
}
6. Error Occurs When Sending Email
For the programmer or a webmaster, to get an email when an error occurs is helpful to take quick action when necessary to improve the existing code. For it could use code such as:
For the programmer or a webmaster, to get an email when an error occurs is helpful to take quick action when necessary to improve the existing code. For it could use code such as:
function customError($errorLevel,$errorMsg){
echo "<b>Error:</b> [$errorLevel] $errstr<br />";
echo "Admin superbly notified";
error_log("Error: [$errorLevel] $errorMsg",1,
"admin@example.com","From: error@example.com");
}
set_error_handler("customError", E_USER_WARNING);
$input = "<strong>bold letters</strong>";
if(preg_match('/<(.+)>/', $input)){
trigger_error("You may not enter html tags", E_USER_WARNING);
}
This method is not recommended for use on any errors that occurred (could lead to spamming). Another errors better stored in a file server or other media.
Summary
PHP has a simple error handling standards. Error sent to the browser shows an error message, the file name, how many lines of code to the scene of the error. PHP provides error handling capabilities better start to use the function die() to use a custom error handler. With the function error_reporting() can be filtered error error what you want displayed. To display the error can not be used function ini_set ('display_errors', 'Off'); and function ini_set ('error_log', 'logs/error.log'); to store the error in the file "logs/error.log", using trigger_error() function to generate custom error messages, and function error_log() to send an email when an error occurs.
PHP has a simple error handling standards. Error sent to the browser shows an error message, the file name, how many lines of code to the scene of the error. PHP provides error handling capabilities better start to use the function die() to use a custom error handler. With the function error_reporting() can be filtered error error what you want displayed. To display the error can not be used function ini_set ('display_errors', 'Off'); and function ini_set ('error_log', 'logs/error.log'); to store the error in the file "logs/error.log", using trigger_error() function to generate custom error messages, and function error_log() to send an email when an error occurs.
Reference
http://www.php.net/manual/en/book.errorfunc.php
http://www.w3schools.com/php/php_error.asp
Found an article helpful? Donate via Paypal
Disclaimer: Images, Content of articles or videos that exist on the web sometimes come from various sources of other media. Copyright is fully owned by the source. If there is a problem with this matter, you can contact us here.
<strong></strong>
or<b></b>
.<em></em>
or<i></i>
.<u></u>
.<strike></strike>
.<code></code>
or<pre></pre>
or<pre><code></code></pre>
, and please parse the code in the parser box below.