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)) { // 執(zhí)行某些操作 } }
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)) { // 執(zhí)行某些操作 } }
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) { // 執(zhí)行很酷的操作 } else { // 不執(zhí)行任何有趣的操作 }
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) { // 執(zhí)行很酷的操作 } else { // 不執(zhí)行任何有趣的操作 }
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

Undress AI Tool
Undress images for free

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

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

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

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

The method of installing PHP varies from operating system to operating system. The following are the specific steps: 1. Windows users can use XAMPP to install packages or manually configure them, download XAMPP and install them, select PHP components or add PHP to environment variables; 2. macOS users can install PHP through Homebrew, run the corresponding command to install and configure the Apache server; 3. Linux users (Ubuntu/Debian) can use the APT package manager to update the source and install PHP and common extensions, and verify whether the installation is successful by creating a test file.

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

To completely destroy a session in PHP, you must first call session_start() to start the session, and then call session_destroy() to delete all session data. 1. First use session_start() to ensure that the session has started; 2. Then call session_destroy() to clear the session data; 3. Optional but recommended: manually unset$_SESSION array to clear global variables; 4. At the same time, delete session cookies to prevent the user from retaining the session state; 5. Finally, pay attention to redirecting the user after destruction, and avoid reusing the session variables immediately, otherwise the session needs to be restarted. Doing this will ensure that the user completely exits the system without leaving any residual information.

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom
