PHP Errors

Errors are normal when you write code, even for experienced developers. What matters is to understand the message, fix the problem, and to handle errors in a safe way on a live website.


Types of errors

TypeWhat it meansDoes the script stop?
Parse (syntax) errorWrong code, like a missing semicolon or bracketYes, the code does not run at all
Fatal errorA serious problem, like calling a function that does not existYes
WarningSomething is wrong but PHP can go on, like using an undefined variable or a missing include fileNo
Notice / DeprecatedA small problem, or you use a feature that will be removedNo

In PHP 7 and above, many fatal errors are thrown as Error objects, so you can catch them with try...catch. Read how to handle errors using try, catch and finally.


Show errors while developing

On your computer you want to see every error. Add this at the top of your script, or set it in php.ini.

<?php
error_reporting(E_ALL);
ini_set("display_errors", "1");

echo $undefinedVariable;
?>

Output:

Sample message, the path will be different

Warning: Undefined variable $undefinedVariable in /path/index.php on line 5


Hide errors on a live website

Error messages can show file paths and other private details to attackers. On a live site hide them, and save them in a log file.

<?php
ini_set("display_errors", "0");
ini_set("log_errors", "1");
error_reporting(E_ALL);
?>

You can also write your own message in the log with error_log("Something went wrong");. See also PHP Security Tips.


Custom error handler

With set_error_handler() you decide what happens when a warning or notice occurs, for example save it in a file or show a friendly message.

<?php
set_error_handler(function ($errno, $errstr) {
    echo "Custom error: [" . $errno . "] " . $errstr;
    return true;
});

echo $undefinedVariable;
?>

Output:

Tutorials Class - Output Window

Custom error: [2] Undefined variable $undefinedVariable

You can create your own error with trigger_error("Message", E_USER_WARNING).


Common errors for beginners

  • Parse error: syntax error, unexpected… Check for a missing ;, ) or } near the line shown.
  • Undefined variable: you used a variable before giving it a value, or the name has a different case.
  • Headers already sent: there was output before header() or session_start(). See PHP header().
  • Failed to open stream: the file path is wrong. See include vs require.
Note: Read the error message and the line number carefully. The real problem is often on the line before the one shown.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What are the different types of error in PHP?
How to force a maximum execution time error in PHP?
How can we set infinite execution time in a PHP script?
How to handle errors using try, catch and finally in PHP?