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
| Type | What it means | Does the script stop? |
|---|---|---|
| Parse (syntax) error | Wrong code, like a missing semicolon or bracket | Yes, the code does not run at all |
| Fatal error | A serious problem, like calling a function that does not exist | Yes |
| Warning | Something is wrong but PHP can go on, like using an undefined variable or a missing include file | No |
| Notice / Deprecated | A small problem, or you use a feature that will be removed | No |
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:
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:
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()orsession_start(). See PHP header(). - Failed to open stream: the file path is wrong. See include vs require.
| Exercises & Assignments |
|---|
| No Content Found. |