PHP programming security summary

  • 2020-03-31 20:16:21
  • OfStack

Rule 1: never trust external data or input

The first thing you must realize about Web application security is that you should not trust external data. Outside data includes any data that is not entered directly by the programmer in PHP code. Any data from any other source (such as a GET variable, form POST, database, configuration file, session variable, or cookie) is not trusted until steps are taken to ensure security.

An easy way to clean up user input is to use regular expressions to process it.

Rule 2: disable PHP Settings that make security difficult to enforce

Having learned that you can't trust user input, you should also know that you shouldn't trust the way PHP is configured on your machine. For example, be sure to disable register_globals. If register_globals is enabled, you might do something careless, such as using $variable to replace a GET or POST string with the same name. By disabling this setting, PHP forces you to refer to the correct variable in the correct namespace. To use the variable from the form POST, you should refer to $_POST['variable']. This way you won't mistake this particular variable for a cookie, session, or GET variable.

The second setting to check is the error reporting level. During development, you want to get as many error reports as possible, but when you deliver the project, you want to log the errors in a log file instead of showing them on the screen. Why? This is because malicious hackers use error reporting information (such as SQL errors) to guess what the application is doing. This kind of spying can help hackers break through applications. To plug this hole, you need to edit the php.ini file, provide the appropriate destination for the error_log entry, and set display_errors to Off.

Rule 3: if you can't understand it, you can't protect it

Some developers use strange syntax, or organize statements in a compact way that forms short, cryptic code. This approach may be efficient, but if you don't understand what your code is doing, you can't decide how to protect it.

Rule 4: "defense in depth" is the new magic

Even if you use PHP regex to ensure that the GET variable is entirely numeric, you can still take steps to ensure that SQL queries use escaped user input.

Defense in depth is not just a good idea, it ensures you don't get into serious trouble.

Related articles: