Errors are undesirable for users and you should do everything in your control to keep users away from them. However, they are of utmost importance for developers. They allow developers to understand the inaccuracies and vulnerabilities in their code by alerting them when their code breaks. They also provide relevant information about what went wrong, where, and what can be done to make amends. Absence of intelligent error reporting can not only make it extremely difficult to debug your project but can also let unnoticed, unresolved inconsistencies bleed into production code.
Most errors in PHP are by default not reported. This might be helpful for web applications in production, where you don’t want users to come across obscure error messages. However, during development, it is imperative to enable error messages – to be alerted about potential inaccuracies in your code before it is released for production.
In this post, we will look at what an error in PHP is, the different types of errors, and how you can enable error reporting in PHP.
Use these links to jump ahead in the tutorial:
Turn on Error Reporting in PHP
What is a PHP Error?
An error is an indication of something going wrong in your web application. It is usually encountered when a part of your code has not been properly implemented, for example – mistakes in the syntax, logical inconsistencies, inattention to handling invalid user input, etc. An error in programming paradigms can be as trivial as a missed semicolon or an unclosed parenthesis to something as big as an undefined class function or an unhandled invalid user input.
Let us look at a few common PHP error categories and codes.
Types of PHP Errors
There are primarily four types of errors in PHP –
- Fatal run-time errors
- Warning errors
- Parse errors (Syntax errors)
- Notice errors
Note: We are able to access error messages in the example outputs shown below because error reporting has been turned on for visualization. We will look at how one can enable error messages in the next section.
Fatal run-time errors (E_ERROR | Code 1)
As the name suggests, these errors can not be recovered from. They are encountered when the operation specified in your code can not be performed. As a result, execution is halted.
For example – if you try to call a function that has not been defined, a fatal run-time error would be raised.
<?php
function foo() {
echo "Function foo called.";
}
boo(); // undefined function 'boo'
?>
Warning errors (E_WARNING | Code 2)
A warning error is more subtle in that regard. It does not halt execution – just acts as a friendly reminder of something incorrect in your code, that might pose a bigger problem in the future.
The most common example of a warning error being raised is when you include a missing file in your code.
<?php
include('filename.txt'); // arbitrary file that is not present
echo "Hello world";
?>
Notice how the warning error has not forced the code to halt, allowing the print statement below to be executed.
Parse errors (E_PARSE | Code 4)
Parse errors are encountered as a result of purely syntactical mistakes in one’s code. These errors are generated during compilation, and as a result your code exits before it is run.
Parse error examples include – missing semicolons, unused or unclosed brackets, quotes, etc. Below is an example of the same.
<?php
echo "Hello world";
echo Hello world // no quotes or semicolon used
?>
Notice errors (E_NOTICE | Code 8)
Notice errors are similar to warning errors in that they are encountered during run-time and they don’t halt code execution. They indicate that something is incorrect in the script that even though doesn’t interrupt execution, should be fixed.
A common example would be trying to use an undefined variable in your code.
<?php
$a = 1;
$c = $a + $b; // undefined variable $b
echo "Hello world";
?>
Turn on Error Reporting in PHP
Error reporting in PHP is usually disabled by default. It can be enabled in three primary ways –
- Directly from code
- By editing the php.ini configuration file
- By editing the .htaccess file.
Before we look into the various methods, a word of caution is necessary. Make sure to disable error reporting for your web application’s production code. You wouldn’t want your users to come across obscure error messages when using your website.
Directly from code
Using the error_reporting() function
To configure error reporting in your PHP project, you can use the error_reporting function. This allows you to manipulate error reporting at run-time.
error_reporting ([ int $level ] ) : int
PHP has various types of errors that we looked at earlier in this post. These types can be provided to the error_reporting function as an argument to specify the kinds of errors that should be reported.
To report all PHP errors you can use the function in any of the two ways shown below.
<?php
// Report all PHP errors
error_reporting(E_ALL);
?>
or
<?php
// Report all PHP errors
error_reporting(-1);
?>
Both of the above-mentioned methods serve the same purpose, and therefore you can use either of them to enable error reporting for all types of errors.
Let us see this in action using an example –
<?php
error_reporting(E_ALL);
echo "Hello world";
// xyz is an undefined variable; should raise an error.
echo $xyz;
?>
OUTPUT:
As we can see, a Notice error has been reported. Had we not used the error_reporting function, PHP would have implicitly taken care of it and not reported anything at all.
This only strengthens our above argument about how unresolved issues can go unnoticed if errors are not appropriately reported.
You can also disable error reporting using the function as such –
//Turn off error reporting
error_reporting(0);
For reporting only specific kinds of errors, you can provide the required error types as a parameter to the error_reporting function using the bitwise OR operator as shown below –
// Report only selected kinds of errors
error_reporting(E_WARNING | E_ERROR | E_PARSE | E_NOTICE);
To enable error reporting for all but one (or more) error levels, you can use the below syntax –
// Report all errors except E_WARNING
error_reporting(E_ALL & ~E_WARNING);
Using the ini_set() function
We can also use the ini_set function to configure error reporting. This function allows us to initialize or modify the various configuration options (specified using a .ini file) directly from our code. This function modifies the configuration options only for the duration of the code (run-time).
You can call this function by adding the following line to your code –
ini_set('error_reporting', E_ALL);
We can similarly manipulate error reporting by applying different values for the ‘error_reporting’ option.
// Report selected kinds of errors
ini_set('error_reporting', E_WARNING | E_ERROR | E_PARSE | E_NOTICE);
Even though the ini_set function allows us to easily modify the configuration options directly from our code, it is a better practice to keep your PHP configurations in a separate php.ini file on your system. Let’s look at how we can do that in the next section.
By editing the php.ini configuration file
The php.ini serves as a configuration file for your project. It is read when PHP is initialized and can be used for a variety of things – storing environment variables, configuring server ports, error reporting, memory management, etc. You can find a list of the various configuration directives and their default values here.
Therefore, to enable error reporting in PHP, you need to edit this configuration file. The php.ini file is usually present in the /etc directory on Linux systems. You can locate the file by printing the output of the phpinfo() function in your code. The file’s path is provided under the ‘loaded configuration file’ row of the output.
Note: If the path mentioned in your output refers to a directory (for example- /etc) and not the file, you can create a new php.ini file inside that directory.
To enable error reporting, you can add either of the following lines to the php.ini file, and restart your server for the effects to take place.
error_reporting = E_ALL
or
error_reporting = -1
To also report errors encountered during PHP’s startup sequence, you can use the following directive in your php.ini file –
display_startup_errors = 1
Some posts on the internet also suggest enabling the ‘display_errors’ option for displaying error messages. In most cases, this is not required since that option is usually turned on by default in PHP.
If it is disabled in your system, you can turn it on by adding the following line in your php.ini file –
display_errors = 1
By editing the .htaccess file
The .htaccess (stands for hypertext-access) is a configuration file for manipulating various options provided by Apache-based web-servers.
Even though it can be a little difficult to set up initially based on your operating system, the .htaccess file allows you to exercise control over various server options at the local directory level and the global system level.
To enable error reporting, add the following two lines to your .htaccess file –
php_flag display_startup_errors on
php_flag display_errors on
Even though (as mentioned above) the display_errors property is by default ON, it is likely that your system admin might have disabled that property globally and you might want to enable it for a local project. Overriding the global property using the local .htaccess file can be a handy approach in such situations.
How to Log Errors in PHP
In large-scale PHP web applications that involve many processes like API requests, data processing etc, it is a good practice to store logs of your output and error messages. Good logging measures allow us to keep track of the inner workings of the system for effective debugging and maintenance. Let’s look at how we can create error logs in PHP.
You need to do two things to store error logs for your project –
- Enable ‘log_errors’ option
- Specify the ‘error_log’ file
Once this has been done, all your errors will be automatically logged to the specified error_log file. Just like error reporting, error logging can be set up from any of these three places – directly from code, from the php.ini configuration file and from the .htaccess file
Directly from code
Using the ini_set function we can configure the relevant PHP options as such –
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file
After doing this, all our errors would be automatically logged to the specified log file. Let us look at an example –
<?php
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file
echo $b; // undefined variable should raise error
?>
Now, let’s open our project root folder and open the ‘my-error-file.log’ file to see if the error message has been logged.
As you can see, a timestamp has also been added to the error message, as we’d expect any effective logging system to do. All errors further encountered in your code will be appended to this file.
Another alternative to logging errors from your code would be to manually do so using the error_log function. You can use the function as shown below to write to a log file as shown below –
<?php
echo "Hello world";
// manually logging error message ->
error_log('My error message ⚠️', 3, 'my-error-file-2.log');
?>
The first and third arguments of the function represent the error message and the log file respectively. The second argument in the above function (3) is an option that specifies that the error message should be appended to the output of the file.
You can read more about the arguments of the error_log function here.
In this case, as can be seen, one has to specify the error message and the logging file each time. Also, in this method, timestamps are not added to the generated log messages by default.
Using the php.ini configuration file
Enabling logging from the configuration file is pretty straightforward. You only need to add two directives to your php.ini file as shown below –
log_errors = on
error_log = /path/my-error-file.log
After saving the file, restart your server to enable the automatic error logging to the specified file.
Using the .htaccess file
You can add the following two lines to your .htaccess file to enable error logging –
php_flag log_errors on
php_value error_log /path/my-error-file.log
This also serves the same purpose – enabling error logging, followed by specifying the output log file.
Conclusion
In this post, we learned about what PHP errors are, their different types (fatal errors, warnings, parse errors, and notices), about how important they are, and how you can enable error reporting for your web application. We looked at three different ways of initiating error reporting and storing log files – directly from code, through the php.ini configuration file, and from the server-based .htaccess file.
Now that you know how important it is to be mindful of errors, go ahead and enable error reporting in your project, maintain error logs, and build yourself a full-proof web application! You can also view your PHP errors in ScoutAPM’s dashboard. Also, make sure to disable error displaying when you release your website for production.
After you have enabled error reporting in your project, you might want to learn about how to handle these raised errors (exceptions) in your code. For this, you can refer to our post on Exception Handling in PHP – PHP Advanced Exceptions.
Stay safe! Keep learning! Happy coding!