The more I begin to try to use PSR-2 coding standards and tools such as GrumPHP (and those related to it), the more I find that the quality of the code I write can be significantly improved in minor ways.

PHP Coding Standards with Code: PSR-2

And I don’t mean to sound contradictory: I mean, the idea of having something “significantly” improved in a “minor” way doesn’t exactly jive, does it?

But hear me out.

Imagine that you’re able to write clean, readable, maintainable code using coding standards that are not only modern, but built into PHP, play nicely with WordPress, and that is more readable than some of the other ways we may have done it in the past or when using other tools for coding standards.

Wouldn’t you be interested?

Sanitize Post Data

Take, for example, the idea of the need to sanitize post data in WordPress. That is, information is sent to the server via a POST request, is contained within the $_POST superglobal, and must be sanitized before having any work done on it.

Sure, WordPress provides a few helper functions for this Рand they are useful Рbut PHP provides some, as well.

Sanitize Post Data: sanitize_text_field

I’ll provide a full gist of the information below in a function that you can reuse in your code. But first, note that I am going to be aggressive. You may not need everything that I’m going to show.

That is, the code you’re going to see will do the following:

  • retrieves a variable for the $_POST superglobal,
  • checks for invalid encoding,
  • encodes various entities, strips all tags, removes line breaks, tabs, whitespaces, and more,
  • quotes a quoted string,
  • removes HTML tags and PHP tags from a string

As I said, not all of this may be needed, and there are other ways to handle some of this depending on how you want to manage your data (for example, see wp_kses).

Sanitize Post Data: wp_kses

There are other times, though, that you may have a settings page that you want to manage before writing data to the database aggressively.

In the code above, the function is used by passing in information that’s found in the $_POST superglobal. It’s then cleaned aggressively using the strategy above and returned as sanitized as possibly can be.

As I said, this can be modified to fit whatever use you need, but if you’re looking for what might be one of the easiest and most aggressive ways to sanitize input from the user, this function may prove useful in your efforts.