- PHP Error Handling
- PHP Error Handling
- Basic Error Handling: Using the die() function
- Example
- Example
- Creating a Custom Error Handler
- Syntax
- Error Report levels
- Set Error Handler
- Example
- Trigger an Error
- Example
- Example
- Error Logging
- Send an Error Message by E-Mail
- PHP show errors in the browser
- Enable error reporting on a PHP file
- Enable error reporting from PHP ini file
- Display PHP error from the htaccess file
- Take your skills to the next level ⚡️
- About
- Search
- Tags
PHP Error Handling
Error handling in PHP is simple. An error message with filename, line number and a message describing the error is sent to the browser.
PHP Error Handling
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:
Basic Error Handling: Using the die() function
The first example shows a simple script that opens a text file:
Example
If the file does not exist you might get an error like this:
Warning: fopen(mytestfile.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2
To prevent the user from getting an error message like the one above, we test whether the file exist before we try to access it:
Example
if(file_exists(«mytestfile.txt»)) $file = fopen(«mytestfile.txt», «r»);
> else die(«Error: The file does not exist.»);
>
?>?php
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
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):
Syntax
Parameter | Description |
---|---|
error_level | Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels |
error_message | Required. Specifies the error message for the user-defined error |
error_file | Optional. Specifies the filename 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 |
Error Report levels
These error report levels are the different types of error the user-defined error handler can be used for:
Value | Constant | Description |
---|---|---|
1 | E_ERROR | A fatal run-time error. Execution of the script is stopped |
2 | E_WARNING | A non-fatal run-time error. Execution of the script is not stopped |
8 | E_NOTICE | A run-time notice. The script found something that might be an error, but could also happen when running a script normally |
256 | E_USER_ERROR | A fatal user-generated error. This is like an E_ERROR, except it is generated by the PHP script using the function trigger_error() |
512 | E_USER_WARNING | A non-fatal user-generated warning. This is like an E_WARNING, except it is generated by the PHP script using the function trigger_error() |
1024 | E_USER_NOTICE | A user-generated notice. This is like an E_NOTICE, except it is generated by the PHP script using the function trigger_error() |
2048 | E_STRICT | Not strictly an error. |
8191 | E_ALL | All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4) |
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.
Set Error Handler
The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script.
It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors:
Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
Example
Testing the error handler by trying to output variable that does not exist:
//error handler function
function customError($errno, $errstr) echo «Error: [$errno] $errstr»;
>
?php
//set error handler
set_error_handler(«customError»);
The output of the code above should be something like this:
Trigger an Error
In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.
Example
In this example an error occurs if the «test» variable is bigger than «1»:
The output of the code above should be something like this:
An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
- E_USER_ERROR — Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
- E_USER_WARNING — Non-fatal user-generated run-time warning. Execution of the script is not halted
- E_USER_NOTICE — Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
Example
In this example an E_USER_WARNING occurs if the «test» variable is bigger than «1». If an E_USER_WARNING occurs we will use our custom error handler and end the script:
//error handler function
function customError($errno, $errstr) echo «Error: [$errno] $errstr
«;
echo «Ending Script»;
die();
>
?php
//set error handler
set_error_handler(«customError»,E_USER_WARNING);
//trigger error
$test=2;
if ($test>=1) trigger_error(«Value must be 1 or below»,E_USER_WARNING);
>
?>
The output of the code above should be something like this:
Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.
Error Logging
By default, PHP sends an error log to the server’s logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.
Sending error messages to yourself by e-mail can be a good way of getting notified of specific errors.
Send an Error Message by E-Mail
In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
//error handler function
function customError($errno, $errstr) echo «Error: [$errno] $errstr
«;
echo «Webmaster has been notified»;
error_log(«Error: [$errno] $errstr»,1,
«someone@example.com»,»From: webmaster@example.com»);
>
?php
//set error handler
set_error_handler(«customError»,E_USER_WARNING);
//trigger error
$test=2;
if ($test>=1) trigger_error(«Value must be 1 or below»,E_USER_WARNING);
>
?>
The output of the code above should be something like this:
And the mail received from the code above looks like this:
This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.
PHP show errors in the browser
Posted on Jul 13, 2022
By default, PHP will try to keep all the warnings and errors from showing on your browser.
This is done so that your users won’t see the errors when using your application.
But to fix an issue found in your code, you may need to display the PHP errors and warnings so that you know what is wrong with your application.
This tutorial will help you to display PHP errors on the browser.
Enable error reporting on a PHP file
To display errors and warnings in your browser, you need to set the following directives at the top of your PHP code file:
The ini_set() function is used to override the configuration in your php.ini file.
In the above example, the display_errors and display_startup_errors configuration is activated by setting their values to true or 1 .
Usually, these configurations are set to false to hide the errors and warnings in your PHP code execution.
Finally, the error_reporting() function determines the error level that will be generated.
- E_ALL — show all errors and warnings
- E_ERROR — show only fatal run-time errors
- E_RECOVERABLE_ERROR — almost fatal run-time errors
- E_WARNING — run-time warnings (non-fatal errors)
- E_PARSE — compile-time parse errors
- E_NOTICE — show run-time notices
- E_STRICT — enable PHP to suggest best practice in your code
- E_CORE_ERROR — fatal errors that occur during PHP’s initial startup
- E_CORE_WARNING — warnings that occur during initial startup
- E_COMPILE_ERROR — fatal compile-time errors
- E_COMPILE_WARNING — compile-time warnings (non-fatal errors)
- E_USER_ERROR — user-generated error message
- E_USER_WARNING — user-generated warning message
- E_USER_NOTICE — user-generated notice message
- E_DEPRECATED — warn about features that will be dropped in future PHP versions
- E_USER_DEPRECATED — user-generated deprecation warnings
But usually, only the E_ALL option is used for debugging your code.
With the three directives set, you should see errors and warnings in your code.
Suppose you have a PHP script as follows:
But keep in mind that setting the directives in the PHP file won’t work when you have a parse error.
Enable error reporting from PHP ini file
A parse error happens when your PHP script is wrong at the syntax level, such as missing semicolons in your code.
Suppose you miss a semicolon as shown below:
Then the page will fail to load on the browser and it will show an HTTP 500 error code:
To make PHP show display parse errors, you need to change the configuration settings in the php.ini file.
If you don’t know where the php.ini configuration file is located, execute the following code from the terminal:
You should see the location of your php.ini file as shown below:
Next, open the php.ini file and set the display_errors , display_startup_errors , and error_reporting configs as shown below:
The configs above are exactly what you set using the ini_set() and error_reporting() functions.
By setting the configs from the .ini file, the parse errors won’t cause PHP to return the error 500 code.
Restart your PHP server, then run the same file again. This time, you should see a parse error message as follows:
That’s how you display all PHP errors and warnings using the PHP ini file.
Alternatively, you can also display PHP errors using the .htaccess configuration.
Display PHP error from the htaccess file
Sometimes, you may not be able to edit the php.ini file because of restrictions from your hosting provider.
In that case, you can try to add error logging configurations from the .htaccess file.
The .htaccess file is a configuration file that you can use to instruct your web server.
This file is usually located in the root directory of your website.
Put the following php_flag configs in your .htaccess file:
Save the configurations, and your web server will follow the .htaccess instructions the next time you run PHP code.
If that doesn’t work, try restarting your web server.
Now you’ve learned how to get PHP to display errors and warnings. Good work! 👍
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with: