As a developer of WordPress plugins or themes, you need to be aware of and use data validation. What is data validation you ask? It’s when you make sure that the data you fetched (POST, GET, database call, external source) is the type of data that you expected. For instance, let’s say you have a user enter a number between 1-10. They enter the letter ‘A’. The process of determining whether the input is an integer between 1-10 is data validation.
So what kind of data functionality does WordPress (and PHP in general) offer? Lots!
- intval($value) – This will cast any value as an integer. Particularly useful for casting floating point numbers.
- absint($value) – Returns the absolute value of a number. For those of you with no math background, that means it will return a whole number given any floating point number. (Ex. absint(3.3) = 3)
- wp_kses() – This function will strip a string of any HTML tags that are not allowed. It also makes sure that any HTML entities that are in the string are normal.
- esc_html($string) – This will escape any HTML characters in a string. This is handy for storing blogs of HTML in a database.
- urlencode($string) – This function encodes any string you put in to it as a url-safe value.
- $wpdb->prepare() – This function is used prepare SQL statements for database inserts. I wrote an article about using the WPDB class with your plugin that you should check out.
- validate_file(..) – This is useful to validate that a file exists, and also to help prevent directory traversal attacks.
- wp_redirect() – This is the safest was to do redirects. Instead of using header(Location: ..), this will only allow redirects to white listed domains instead domains.
- balanceTags($string) – If you’re allowing your users to comment on something with html tags, this function will try to make sure that the tags are balanced.
- is_email($email) – Validates whether an email address is valid or not.
As you can see, WordPress (and PHP) include a nice array of data validation functions. Make sure you use them as often as possible, because a large number of web based attacks could be prevented if people validated data.
2 replies on “WordPress Data Validation Functions”
Previously, plagiarised content often ranked higher than the original piece.
I have just wasted over an hour playing around with a new site – a new site that I have no time
to build. include organic SEO, Reciprocal and one way
link building, web based content writing for online submissions, Blogging and the
Nice info. Thanks for that.
I have a question. wp_kses santizes the html with the allowed html element but it also strips off the class associated with the allowed htmls.
$html = ‘error:Enter an email.’;
echo wp_kses( $html, array( ‘p’ => array(), ‘strong’ => array() ) );
the above will output
error:Enter an email.’
Any idea what to do to have the class too.
Thanks in advance.