PHP Warning and Errors
PHP generates different types of errors and warning depending on the problem. Knowing how to read these errors and warnings can make resolving the problem make easier. Of course, the first step it make sure we can see these errors and warnings.
Display Errors
By default, PHP will not display errors or warnings. If we can see the errors and warning we can deal with them. So we will want to make sure that PHP is reporting all error to us in development.
There are two ways to do this: add a line of code to the top of our PHP file OR to set error reporting in a php.ini
file.
NOTE
Displaying errors and warning during development is crucial for debugging our code. But, they should NOT be displayed in production.
In the php.ini File
The preferred way to set the error reporting for PHP is through the php.ini
. The location of this file will vary depending on your server configuration. So, please refer to the [PHP Server] module for more information.
Once you have the php.ini
file open in your text editor, search for the line containing display_errors =
. Make sure the value is set to On
and that the line is not commented out.
display_errors = On
Next, search for error_reporting
. Make sure the value is set to E_ALL
and that the line is not commented out.
error_reporting = E_ALL
In the PHP Code
If the php.ini
is not accessible, it is possible to set error reporting in the PHP code. Just at the following lines to the PHP file you want error reporting.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
?>
PHP Linter
Another way to catch PHP errors, especially syntax errors is by using a PHP Linter. A linter is a small program that makes sure our code is well formatted and free of errors.
Visual Studio Code uses the official PHP Linter, out of the box, to provide live code feedback. This means has you type Visual Studio Code will provide highlighting and error messages if a syntax error is made.
View the documentation to learn more about PHP Linting with Visual Studio Code
Type of PHP Errors
There are 5 categories of errors that PHP will report and display. They are Fatal Errors, Parse Errors, Warnings, Notices, and Deprecated.
Fatal Errors
Fatal runtime errors will kill the page completely. Common fatal runtime errors include running out of memory.
Parse Errors
Parse errors or syntax errors occur during compile time, and therefore occur before anything is sent to the page.
Warnings
Warnings are non-critical problems and typical will not kill the page. Warnings are an indication of poorly written code.
Notices
Notices are not problems, but is PHP way of providing advice. Like warning, notices can be an indication of poorly written code.
Deprecated
Is a notice that a method or statement being used will be removed from PHP in future versions and updated or replaced.