Error types and error reporting in PHP

Hamid Haghdoost - Dec 4 '22 - - Dev Community

It is important to know about error types in PHP. By this knowledge it would be easier to find and solve errors. Basically we have 4 types of error in PHP and I will show you them with an example.

1. Notice

PHP is not sure about whether is it an error or not!

2. Warning

An error that is important and should be fixed but does not stop code execution.

include("external_file.php");

Warning: include(external_file.php): Failed to open stream: No such file or directory in /Users/hamid/Codes/error.php on line 4
Enter fullscreen mode Exit fullscreen mode

3. Parse error

When the compiler is unable to parse your code correctly. For example when a ; is missing.

if ($a == 1) {
    echo "something!"
}

Parse error: syntax error, unexpected token "}", expecting "," or ";" in /Users/hamid/Codes/error.php on line 12
Enter fullscreen mode Exit fullscreen mode

4. Fatal error

When you have a critical error. Your code execution will be halted.

$c = 1 / 0;

Fatal error: Uncaught DivisionByZeroError: Division by zero in /Users/hamid/Codes/error.php:7
Stack trace:
#0 {main}
  thrown in /Users/hamid/Codes/error.php on line 7
Enter fullscreen mode Exit fullscreen mode

Error reporting in PHP

You can ask PHP to show specific types of errors like these:

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
Enter fullscreen mode Exit fullscreen mode

Thank you for reading...

. . . . . . . . . . .