phpmaster | Error Handling in PHP
Key Takeaways
- PHP error handling is crucial for maintaining the integrity and functionality of a web application. It helps identify and fix issues that may arise during script execution, improving user experience by controlling what they see when an error occurs.
- PHP offers several built-in functions for error handling, including logging and displaying them. It also provides flexibility to customize error handling strategies by registering error handlers and using exceptions.
- Custom error handling in PHP can be achieved using set_error_handler() and set_exception_handler() functions. These allow developers to define custom error handling rules and exceptions, which can be useful for logging errors or sending error notifications.
- Exceptions in PHP are events that occur during script execution, disrupting the normal flow of instructions. They can be handled using try, catch, and finally blocks. If no catch block is found when an exception is thrown, PHP will display a fatal error and stop executing the script.
PHP Error Reporting Levels
All errors and warnings should be logged. Based on the severity of an error, notifications should be sent out to other systems/teams. So that you can better gauge its severity, PHP provides several built-in error levels to describe the nature of an error. Each level is represented by an integer value and named constant which can be used by the programmer. The table below is taken from the official PHP documentation and shows some of the different levels.Creating Custom Error Handlers
It’s also good practice not to display raw errors to the end user. Errors that are displayed should be abstracted with friendly, custom error messages. PHP not only provides built-in functions for logging and displaying errors, but also for raising them. You can pragmatically trigger an error of a specific level using trigger_error(). For example, this code triggers an E_USER_NOTICE warning if the value of $test is greater than 1:<span><span><?php </span></span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error('Value of $test must be 1 or less', E_USER_NOTICE); </span></span><span><span>}</span></span>
handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
<span><span><?php </span></span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error('Value of $test must be 1 or less', E_USER_NOTICE); </span></span><span><span>}</span></span>
Handling Errors using Exceptions
However good of an error handling framework you have in place, there will always be problems at run-time. Of course you don’t want these errors to show up in the user’s browser. This is where exception handling enters the picture. Exceptions allows you to handle errors and exceptional situations gracefully. Exceptions are represented in PHP by the class Excpetion (or any of its subclasses). They can be raised using throw and can be caught using a try/catch block. You can extend Exception to create custom exception types for trapping specific errors. The code that may trigger an exception is placed within the try block, and the code to handle the exception is placed within the catch block. Consider the following snippet:handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
Creating a Custom Exception Handler
PHP will let you throw any object as if it were an exception, but as a rule of thumb the exception should extend PHP’s built-in Exception class. Based on the object’s type, you can handle the exceptions differently. Custom exception handling can perform suitable actions like logging error messages in file, providing exact details about the line on which the error occurred by examining the calling stack, etc. Have a look at this example:<span><span><?php </span></span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error('Value of $test must be 1 or less', E_USER_NOTICE); </span></span><span><span>}</span></span>
Re-throwing Exceptions
try/catch blocks can be nested. Sometimes you’ll want to catch an exception, look at some of its properties, and then throw it again to let a parent catch block handle it. This can often be useful to check an error condition and decide whether it should be fatal or not. This example code demonstrates re-throwing an exception:handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
Uncaught Exception Handler
Similar to how set_error_handler() allows you specify a function to handle run-time errors, the set_exception_handler() function allows you to handle exceptions that make it all the way up the call stack without being caught by any catch blocks. For example, if an exception makes it all the way up your stack, it would be a good idea to log it in a log file. You can create a callback function and register it with set_exception_handler() as shown in the example below.<span><span><?php </span></span><span><span>function errorHandler($errno, $errstr, $errfile, $errline) { </span></span><span> <span>static $db; </span></span><span> <span>if (empty($db)) { </span></span><span> <span>$db = new PDO(DSN, DBUSER, DBPASS); </span></span><span> <span>} </span></span><span> </span><span> <span>$query = "INSERT INTO errorlog (severity, message, filename, lineno, time) VALUES (?, ?, ?, ?, NOW())"; </span></span><span> <span>$stmt = $db->prepare($query); </span></span><span> </span><span> <span>switch ($errno) { </span></span><span> <span>case E_NOTICE: </span></span><span> <span>case E_USER_NOTICE: </span></span><span> <span>case E_DEPRECATED: </span></span><span> <span>case E_USER_DEPRECATED: </span></span><span> <span>case E_STRICT: </span></span><span> <span>$stmt->execute(array("NOTICE", $errstr, $errfile, $errline)); </span></span><span> <span>break; </span></span><span> </span><span> <span>case E_WARNING: </span></span><span> <span>case E_USER_WARNING: </span></span><span> <span>$stmt->execute(array("WARNING", $errstr, $errfile, $errline)); </span></span><span> <span>break; </span></span><span> </span><span> <span>case E_ERROR: </span></span><span> <span>case E_USER_ERROR: </span></span><span> <span>$stmt->execute(array("FATAL", $errstr, $errfile, $errline)); </span></span><span> <span>exit("FATAL error <span><span>$errstr</span> at <span>$errfile</span>:<span>$errline</span>"</span>); </span></span><span> </span><span> <span>default: </span></span><span> <span>exit("Unknown error at <span><span>$errfile</span>:<span>$errline</span>"</span>); </span></span><span> <span>} </span></span><span><span>} </span></span><span> </span><span><span>set_error_handler("errorHandler"); </span></span><span> </span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error("Value of <span><span>$test</span> must be 1 or less"</span>, E_USER_NOTICE); </span></span><span><span>}</span></span>
Summary
PHP offers variety of built-in functions for handling error conditions, including logging and displaying them. It also provides you the flexibility to customize your error handling strategies by registering error handlers and using exceptions. Errors are a fact of life, but hopefully the information I presented in this article will help you handle them more gracefully. Image via Ilya Andriyanov / ShutterstockFrequently Asked Questions (FAQs) about Error Handling in PHP
What is the importance of error handling in PHP?
Error handling in PHP is crucial for maintaining the integrity and functionality of a web application. It helps developers identify and fix issues that may arise during the execution of a script. Without proper error handling, a minor issue can cause significant problems, such as crashing the application or exposing sensitive information to users. It also improves the user experience as it allows developers to control what the user sees when an error occurs, rather than displaying confusing error messages.
How does PHP handle errors by default?
By default, PHP sends an error report to the server’s error log and displays an error message on the screen. This behavior is not ideal for a live website because it can reveal sensitive information to the user. Therefore, it’s recommended to change the default error handling settings for a live website.
What are the different types of errors in PHP?
PHP classifies errors into several types, including fatal errors, warnings, parse errors, and notices. Fatal errors are critical errors, such as calling a non-existent function or writing to a file that isn’t writable. Warnings are non-fatal errors that allow the script to continue running. Parse errors occur when there’s a syntax mistake in the script. Notices are minor errors or possible errors that PHP encounters while executing a script.
How can I customize error handling in PHP?
PHP provides several functions to customize error handling, such as set_error_handler() and set_exception_handler(). These functions allow you to define custom error handling rules and exceptions. You can specify a custom function to handle errors, which can be useful for logging errors or sending error notifications.
What is an exception in PHP?
An exception is an event that occurs during the execution of a script that disrupts the normal flow of the script’s instructions. When an exception is thrown, PHP will stop executing the script and start looking for a catch block to handle the exception. If no catch block is found, PHP will display a fatal error and stop executing the script.
How can I handle exceptions in PHP?
PHP provides the try, catch, and finally blocks to handle exceptions. The try block contains the code that may throw an exception. The catch block contains the code to handle the exception. The finally block contains the code that will be executed regardless of whether an exception was thrown or not.
What is the difference between errors and exceptions in PHP?
The main difference between errors and exceptions in PHP is how they are handled. Errors are handled by the PHP engine and can be controlled using error reporting settings and custom error handlers. Exceptions, on the other hand, are handled by the script and can be controlled using try, catch, and finally blocks.
How can I turn off error reporting in PHP?
You can turn off error reporting in PHP by using the error_reporting() function with 0 as its argument. However, turning off error reporting is not recommended for a live website because it can make it difficult to identify and fix issues.
What is the role of the @ operator in PHP error handling?
The @ operator in PHP is used to suppress error messages. When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
How can I log errors in PHP?
PHP provides the error_log() function to send an error message to the server’s error log or to a specified file. This function can be useful for keeping track of errors and debugging. You can also configure PHP to log all errors by changing the log_errors directive in the php.ini file.
The above is the detailed content of phpmaster | Error Handling in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The arrow function was introduced in PHP7.4 and is a simplified form of short closures. 1) They are defined using the => operator, omitting function and use keywords. 2) The arrow function automatically captures the current scope variable without the use keyword. 3) They are often used in callback functions and short calculations to improve code simplicity and readability.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
