Stackify is now BMC. Read theBlog

PHP Error Handling Guide

By: jmendez
  |  March 14, 2024
PHP Error Handling Guide


Because PHP is free to use, many web developers use this programming language to make web applications. Even the most popular web content management systems are based on this programming language. Handling errors in PHP is almost the same as handling errors in other programming languages. But if a developer is new to the language, seeing the errors for the first time can be scary and annoying. Below is an example.

if $x==1 {
    echo "Hello World!";
}

Parse error: syntax error, unexpected '$x' (T_VARIABLE), expecting '('

Syntax error messages in PHP are comparable to syntax errors in other languages. Anyone with the knowledge about this language will be able to trace and fix this error.

PHP Error Handling Tutorial

In this article, you’ll learn about the different types of errors including error logs, error handling, error handling functions, and other error PHP framework error handling. Let’s start by defining the difference between the terms “error” and “exception” and other common terms in PHP.

Errors vs. Exceptions

Many use error handling and exception handling interchangeably.  When we say error handling we are referring to the process of catching errors produced by your program which needs proper action. Since PHP came into a new object-oriented (OOP) way of dealing with errors, exception handling was introduced. It is used to change the usual way of handling code execution of a specific error condition when it occurs. In this way, exception handling provides a better technique over error handling.

How does exception handling in PHP  work?

Just like any other object-oriented programming, PHP also uses the following keywords related to exceptions:

Try:  this means that if the exception does not trigger, the code will just execute normally but if the exception triggers then it will call “thrown” exception

Throw: every time an exception has been triggered, a “throw” exception must be paired with at least one “catch”

Catch:  this block of code should retrieve an exception and create an object including the exception information.

Error logs

Error logs are crucial during development because this allows developers to see the errors, warning, notices, etc. that were logged while the application is running. Most of the time, when a web application is deployed, all errors and warnings are suppressed to prevent ordinary users from seeing the errors that will arise. Even though the errors and warnings are hidden from the regular users, the web server still logs every event the website encounters.

Simple error handling

Whenever the application is in an incorrect state in which it cannot recover, then the program is in an error state.

// Set MySQLi to throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $connection2 = mysqli_connect('localhost', 'root1', 'Abc123456!', 'testx');
} catch (mysqli_sql_exception $ex) {
    throw new Exception("Can't connect to the database! \n" . $ex);
}

Fatal error: Uncaught Exception: Can't connect to the database! mysqli_sql_exception: Access denied for user 'root1'@'localhost' to database 'testx'

Because the parameters for the mysqli_connect are incorrect, the best way to handle this kind of scenario is the program throwing an exception. It’s pointless that the application continue executing because it would not still return some data from the database.

Using die() or exit() for handling errors

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $connection2 = mysqli_connect('localhost', 'root1', 'Abc123456!', 'testx');
} catch (mysqli_sql_exception $ex) {
    die("Can't connect to the database! \n" . $ex);
}

During development, using the function die or exit to halt code is a go-to-coding style for developers. In code and even tutorials, when connecting through a database, if the connection is incorrect or invalid, then the application calls either of these two functions to halt the execution of the program. This is very helpful in handling errors and tracing code, but when the application is deployed, this might scare the ordinary users of the web application. Errors like “Fatal error: Uncaught Exception: Can’t connect to the database! Mysqli_sql_exception” is not helpful to the end user. When the code that handles the database connection uses die or exit, then there is no way to suppress these error messages on the live web server. Exceptions, notices, etc. can be hidden with just a simple web server configuration or additional PHP code that’s why throwing exceptions is more practical in handling PHP errors.

Retrace error logging

error logging

In Retrace, all errors are recorded together with some important information about that error like the time it occurred, the method that caused it, and the exception it generated. The number of times the error occurred in a particular time frame is also graphed. From this data, developers can easily look at what caused the error and then apply a fix. Project managers can also prioritize which issue to fix based on the number of occurrence of an error.

PHP error handling functions

function myTestFunctionHello($str)f
{
    echo "\nHi: $str";
    myTestFunctionGoodbye($str);
}

function myTestFunctionGoodbye($str)
{
    echo "\nGoodbye: $str";
    print_r(debug_backtrace());
}

myTestFunctionHello('World');

// output
{[0]=> array(4) { ["file"]=> string(43) "\var\www\test-error.php" ["line"]=> int(6) ["function"]=> string(21) "myTestFunctionGoodbye" ["args"]=> array(1)
{ [0]=> string(5) "World" }
}
[1]=> array(4){ ["file"]=> string(43) "\var\www\test-error.php" ["line"]=> int(15) ["function"]=> string(19) "myTestFunctionHello" ["args"]=> array(1)
{ [0]=> string(5) "World" }
}}

The debug_backtrace allows developers to see which function was called first. Essentially, this will return an array of function calls, lines, objects, class, etc. This is helpful in tracing errors because any fix made can affect the other functions that calls or use it. A similar function, debug_print_backtrace, also gives similar output but with more details.

echo $unknown_a;
echo $unknown_b;
print_r(error_get_last());
Array ( [type] => 8 [message] => Undefined variable: unknown_b [file] => C:\xampp\htdocs\monolog-test\test-error.php [line] => 4 )

The function error_get_last will get the last error in the stack trace. This can be used to remove all the other errors displayed in the stack trace and only focus on the last error that has occurred.

// will log to the web server error log file, will also log to Retrace
error_log("This is a sample error.", 0);

// will email the error log
error_log("This is a sample error.", 1, "[email protected]");

// will log an error to a specified file
error_log("This is a sample error.", 3, "my-errors.log");

The error_log function allows developers to log errors in either the default error log of the web server, send the error log to an email, or log the error to a specified file.

$divisor = 0;
if ($divisor == 0) {
    trigger_error("Division of zero not allowed!", E_USER_ERROR);
}

Fatal error: Division of zero not allowed! in C:\xampp\htdocs\monolog-test\test-error.php on line 5

This will generate a user defined error, notice, warning etc. This PHP function allows developers to generate a specified response at runtime.

Other PHP framework error handling

In other PHP frameworks, error handling is a lot easier and most of them are just a matter of editing the configuration file. In Laravel, the class App\Exceptions\Handler handles all the triggered exceptions and logging by a web application. The Handler class in Laravel has two methods, report and render. The report method is used to send exceptions to an external service. The report is good for logging errors without displaying it in a web page. The render method will convert an exception into an HTTP response that needs to be sent back to the browser.

abort(500);
abort(403, 'You are not allowed to enter!');

Throwing HTTP exceptions can easily be done in Laravel by using the abort helper. The abort helper function has an optional response text parameter for a custom display message.

Conclusion

Errors and troubleshooting take time and headache during development and even in the deployment of your app. The right tool to handle errors makes your life easier. Stackify combines debug object logging with error logging, which can easily check the root cause of your exceptions. Stackify’s error and log management tool can help you easily monitor and troubleshoot your application. You can try our 14 day free trial now!

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]