More Tips for Defensive Programming in PHP
Build a robust PHP application: Defensive programming strategy
This article explores the importance of defensive programming in PHP development and provides some key strategies to improve the robustness and efficiency of applications. Defensive programming is not to avoid test-driven development, but to foresee and avoid potential failure points before problems occur.
Core points:
- Defensive programming is designed to predict potential failure points and take measures to circumvent them before they occur.
- "Fast Failure, Report an Error loudly" is an effective defensive programming method. Errors should appear early and alert them, especially when processing user input or input from external systems such as APIs.
- Input verification, preventing unexpected assignments in comparisons, try/catch exception handling, and database transactions are key aspects of defensive programming.
Definition of defensive programming:
Defensive programming, simply put, is to program for the purpose of predicting potential failure points. The goal is to circumvent these problems before they occur.
Many people oppose defensive programming, but this is often because of some of the defensive programming methods they see. Defensive programming should not be seen as a way to avoid test-driven development or simply to fix failures.
"Fast Failure" should not be considered an opposite of defensive programming. Both belong to the same category. What are these methods if not to predict the possible failure of the program and to prevent or properly handle these failures?
Fast quickly, report an error loudly
Simply put, "failed quickly, reported an error loudly" means that when an error occurs, it will occur as early as possible and alert the person concerned, rather than silently continuing to run in the error state, which may cause more problems .
This method is most useful when processing user input or input from scripts, modules, or outside the system (e.g. through the API). One application scenario is to check for invalid values or data types passed to a function.
function thisTestFunction($testInt) { if (!is_int($testInt)) { // 执行某些操作 } }
One of the errors that some programmers use the "fast failure" method is simply throwing exceptions and errors to the user without properly preparing for handling them. You don't want the average user to be worried or confused by your error message. More importantly, you don't want malicious users to learn anything from the information they are displayed to them. Show the user a helpful message, log your error, and perform any other tasks that need to be the result of that exception. You don't want just fastfailure, you also need loud (know that there is a problem) and security (don't let you have bad exception handling or total lack of exception handling cause more security issues) .
Input verification
There are many ways to safely verify user input.
Type conversion is an interesting way to "verify" user input. Sometimes it looks like this:
function thisTestFunction($testInt) { if (!is_int($testInt)) { // 执行某些操作 } }
Instead of using other methods to avoid cross-site scripting attacks, it simply captures, type converts and assigns values. This only works if you have the expected type and any value of that type is safe (otherwise, you also need to check the proper integer value). I think the problem with this approach (in most cases) is that you are not really checking the input, but just force it becomes what it should be. This may have unintended consequences. Instead, a better approach might be to use filter_input()
to check the appropriate value.
$member->property = (int)$_GET['property'];
There are many benefits to using native filter_input
functions in modern PHP, you can learn more in the above article or on php.net.
Prevent unexpected assignments in comparison
This is a simple and often noticed defensive programming principle. Making simple changes in how you compare can have a huge impact. Consider the following situation:
$member->property = filter_input(INPUT_GET, 'property', FILTER_VALIDATE_INT); if (false === $member->property) { throw new Exception('Property was not an int'); }
This is a relatively normal comparison, right? But what happens if you accidentally use "=" instead of "==" (or, in most cases, better "==")? Simple swipe of fingers on the keyboard? Forgetful, maybe? Suddenly, your comparison is always, in all cases, true. Unless your IDE warns you this, how long will it take for you to discover it? In some cases, this can be a silent error for a while. However, there is an extremely simple way to prevent this:
if ($member->property == 12345) { // 执行很酷的操作 } else { // 不执行任何有趣的操作 }
Now, if you accidentally use an equal sign, the error will not be silent. Obviously, this may not happen often, it may be mitigated by your tests and is not practical in all cases, especially when doing variable-to-variable comparisons. But if you tend to happen, this is still not a bad idea.
Handle Try/Catch and Exceptions
try/catch statement is another hot topic among PHP developers. Let's first take a quick look at what we're discussing.
if (12345 == $member->property) { // 执行很酷的操作 } else { // 不执行任何有趣的操作 }
A well-known tool for defensive programming is the try/catch statement and the Exception class. When used correctly, they are great for catching and logging errors. A good programmer will use the try/catch statement to predict errors or other situations that may cause interruption of normal processes. When these exceptions occur, they must be handled in an appropriate manner. If required, users of the application should receive reasonable error messages as useful as possible without leaking sensitive information. The application's administrator should receive detailed alerts and/or logs. Unprocessed or ignored exceptions ignore the suggestion of "reporting an error loudly" and may allow the program to be in a silent error state for a period of time in nature, which is not good for any person involved.
Business
Transactions are a feature of databases that allow queries to be grouped together so that if one query fails, all queries fail. This is the implementation of ACID, and you can read more about it here. The idea is that combining multiple queries into one process can sometimes be a safer and more stable solution, especially when queries are interdependent. PHP developers often ignore transactions entirely, or assume they are unnecessary, but some defensive programming can go a long way when interacting with a database. Transactions are discussed in more depth in this article, but in short, transactions allow you to run MySQL updates and then check the results before the actual commits results. If you are using PDO (you should), you can start the transaction using the PDO method, commit the result, and roll back. In addition to the above summary of transactions, they can be further studied through this in-depth guide.
Conclusion
These are just some common tricks. Obviously, each of them has its purpose, and each has its significant situation where it does not apply. But if you incorporate these concepts into your everyday development regime, it can increase the efficiency of your work. While this is usually a topic that is more suitable for developers currently learning PHP, for everyone, it is a good review of practice.
If there is only one thing that is remembered, especially for newer developers, it is that you should do defensive programming – a plan that may be wrong. Handle them properly. Don't let silent errors continue to develop. Failed quickly. Test your code. By building robust applications that test and solve problems, and predict and handle future problems, you can make your applications more reliable and hopefully help create a better user experience behind the scenes.
The above is the detailed content of More Tips for Defensive Programming 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

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

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.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
