Security
Your code works! But is it safe? Is there a chance that through your plugin, a malicious user could gain access to the site? Keep in mind that your code could be running on hundreds, maybe even millions of sites, so security is paramount.
Special attention to security should be given when:
- creating the plugin settings page.
- creating shortcodes.
- saving data to the database.
- outputting data to the screen.
I will highlight three models to follow to ensure code security.
1. Safe Input
Every time PHP code receives some data:
- the user submits data to WordPress via a form.
- data is imported from an internal or external source.
- an AJAX request is processed.
- data comes to WordPress through various APIs.
It is very important to ensure that this is safe. This can be done by validating and sanitizing data.
2. Output Sanitization
Every time the post title, meta data, or any other data is provided to the user - output to the screen, it needs to be sanitized. Sanitization is necessary to prevent attacks such as Cross-Site Scripting (XSS - cross-site scripting).
In WordPress, a number of functions are provided for this sanitization all of which start with the prefix esc_, for example esc_html().
3. Access Control Check
To prevent unauthorized changes to plugin settings or actions that the user is not allowed to perform, access rights must be checked.
WordPress offers two ways:
-
user capability checks - see current_user_can()
- nonces - see all nonce functions
Both types of protection should be used together, i.e., one complements the other...
Useful Links on WordPress Security
-
How to fix the intentionally vulnerable plugin by Jon Cave
- Mark Jaquith’s Theme and Plugin Security presentation