Home > Backend Development > PHP Tutorial > More Tips for Defensive Programming in PHP

More Tips for Defensive Programming in PHP

Jennifer Aniston
Release: 2025-02-16 10:34:10
Original
1110 people have browsed it

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?

More Tips for Defensive Programming in PHP

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)) {
        // 执行某些操作
    }
}
Copy after login
Copy after login

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)) {
        // 执行某些操作
    }
}
Copy after login
Copy after login

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'];
Copy after login

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');
}
Copy after login

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 {
    // 不执行任何有趣的操作
}
Copy after login

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 {
    // 不执行任何有趣的操作
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template