Error handling is the process of catching errors from the program and then taking appropriate action. Before proceeding for error handling you should get to know how many types of errors occurred in PHP.

Notices: These are non-critical errors that occurred while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although, as you will see, you can change this default behavior.

Warnings: These are more serious errors – for example, attempting to use a file (using include() method) which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

Fatal Errors: These are critical errors – for example, creating an object of a non-existent class, or calling a function which doesn’t exist in your program. These errors cause the immediate termination of the script, and PHP‟s default behavior is to display them to the user when they take place.

It’s very simple in PHP to handle errors.

Using die() function

While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Example

<?php

if(!file_exists(“/docs/resume.txt”))

{

die(“File not found”);

}

else

{

$file = fopen(“/docs/resume.txt”,”r”);

}

?>

Some possible errors in PHP

E_ERROR – Fatal Run-time errors. Execution of the script is halted

E_WARNING – Non-fatal errors. Execution is not halted

E_PARSE – Compile-time parse errors.

E_NOTICE – Run-time notices.

E_ALL – All errors and warnings, except level E_STRICT

E_CORE_WARNING – Non-fatal run-time errors. This occurs during PHP’s initial start-up.

 There are some different locations where we can control errors:

In the php.ini file

In the .htaccess file on your web server

From your own PHP code.

We could do the same from our PHP code during runtime by calling the error_reporting() function as below:

 error_reporting(E_ALL);

 To turn on error logging and log the errors to our specific log file (instead of the default error log file, which is often the web server error log file)

 log_errors = on

error_log = “/tmp/error.log”