saftutorials.com
PHP ERROR HANDLING

Error handling is the very important part of PHP. It is a process catching errors raised by your program. If you will not handle the error of your code, then your code will look like an unprofessional.


Error handling is the very simple process in PHP


Example of error handling by using PHP die() and file_exist() function

<?php
$file=fopen("test.txt","r");
?>

If test.txt file does not exist then you get an error like this

The above code produces the following results

Warning: fopen(test.txt) [function.fopen]: failed to open stream: No such file or directory in C:\projectname\test.php on line 2


<!DOCTYPE html>
<html>
<body>
<h1>Error Handling example</h1>
<?php
if(!file_exists("test.txt")) {
die("File does not exist");
} else {
$file=fopen("test.txt","r");
}
?>
</body>
</html>

And now if exist then the file will open in reading mode and if not exist then an error will display like this.

The above code produces the following results

Outputs: File does not exist


Define Custom Error Handling Function


You can handle error of code by using write your custom function.php provides you a framework to define error handling function.


This function can accept up to five parameters in which two parameters are required and left three are optional.

Required parameters are error_level and error_message.


Syntax of PHP error_function() function

error_function(error_level, error_message, error_file, error_line, error_context);

error_level    (Required - Specifies the error report level for the user-defined error. Must be a value number.)

error_message  (Required - Specifies the error message for the user defined error)

error_file     (Optional - Specifies the file name in which the error occurred)

error_line     (Optional - Specifies the line number in which the error occurred)

error_context  (Optional - Specifies an array containing every variable and their values in use when the error occurred)


Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. 

E_ERROR                          1      (Fatal run time error)

E_WARNING                      2      (Nonfatal run time error) 

E_PARSE                           4      (Compile time parse error)

E_NOTICE                         8      (Run time Notice)

E_USER_ERROR                 256    (Fatal user generated error)

E_USER_WARNING             512    (Nonfatal user generated warning)

E_USER_NOTICE                1024   (User generated notice)

E_STRICT                          2048   (Run time notices)

E_RECOVERABLE_ERROR    4096   (Catchable fatal error)

E_ALL                               8191   (All errors and warnings)


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic