Your shopping cart is empty!
When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
This tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods:
The first example shows a simple script that opens a text file:
If the file does not exist you might get an error like this:
To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:
Now if the file does not exist you get an error like this:
The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.
Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):
These error report levels are the different types of error the user-defined error handler can be used for:
Now lets create a function to handle errors:
The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
Now that we have created an error handling function we need to decide when it should be triggered.