This is day 12 of my WordPress Developer Advent Calendar.
When developing WordPress plugins it is always a good idea to be thoughtful about security. Follow these simple tips to harden your plugin:
Validate User Input
When you get data back from a user, validate it! There are a number of useful functions to help with input validation. For example:
- Use intval() when you expect numbers
Depending on the context, data must be sanitized when displayed back to the user. Again, WordPress has a number of helpful functions to make this easy. For example:
You must be sure that when data is posted to WordPress, that you know where that data came from. Nonces help you “trust” a source. You can add a nonce to a URL using wp_nonce_url() or add a hidden nonce filed to your form using wp_nonce_field(). You can then verify the nonce by using check_admin_referer.
Prepare SQL Queries Correctly
Firstly, when writing your own SQL to query the database, make sure you escape the queries using $wpdb->prepare. Secondly, and more importantly, pass your variables as arguments to the prepare function. DO NOT append, concat or do any manual string manipulation to your queries. Let the prepare method do it’s thing and escape the variables for you.
For example, this is BAD:
"INSERT INTO employee (username, name) VALUES ('$username', '$name')" )
This should rather be written like this:
"INSERT INTO employee (username, name) VALUES (%s, %s)", $username, $name )
Trust WordPress Functions
When possible (and most times it is possible) use the built-in WordPress functions. These functions have been tried and tested and offer the most secure way to accomplish a specific task. For example, use the get_posts function rather than writing a custom select query and passing that to $wpdb->get_results.
It is always wise to check that a user can perform a certain task before doing it. You never know, if a user somehow manages to run your top secret function, they could potentially do something malicious. So check they have the correct capabilities first, using current_user_can(), then you can safegaurd yourself against any possible issues.
Check out these other resource to learn more and get more clued up:
- Mark Jaquith: Theme & Plugin Security
- Brad Williams: Writing Secure WordPress Code
- Data Sanitization And Validation Within WordPress
- Review an intentionally vulnerable plugin, and then how to fix it.