When you develop a wordpress plugin, a important thing is hope your users are always safe. A few years before, we had to use a few functions like addslashes, stripslashes, or something like $wpdb->escape($var) to avoid security problem come from user side. Fortunately for wordpres developers, in recent years, wordpress have improve their security quickly, wordpress team have did a lot of work to make this more easier for developers.
How to Security Your WordPress Plugin?
When you want to avoid attack from un-authorized users, you can use WordPress Nonces, what is Nonces? It means “number used once”, it looks like a random number like ’43a45ab95c’(actually it is not a number, it is a hash made up of numbers and letters, the nonce is generated based on the current time), in your URLs or forms, if you use WordPress Nonces, you will find a “tail” like ” _wpnonce=43a45ab95c”, in server end, if the number is not right, you can stop insert data into your database or show more things to the un-authorized users, by this way you can stop “Cross Site Request Forgery“.
How to add WordPress Nonces in your plugin?
It is very easy, if you want to redirect user to a URL, in general we use ‘wp_safe_redirect’ function like this:
So you will redirect your users to https://.bz/wp-admin/admin.php?page=Announcements
What you need to do is add a nonce tail in your URL, you can use codes like this:
$an_url = get_option(‘siteurl’) . ‘/wp-admin/admin.php?page=Announcements’;
$an_url = wp_nonce_url($an_url);
The function wp_nonce_url will add a wordpress Nonces for at the end of your URL, it will looks like this
And this will help to protect URLs from certain types of misuse, malicious or otherwise.
Also you will need use the similar method to protect your forms
If your plugin use forms, you need add WordPress Nonces too, this is very easy, just two steps:
1: Before the submit button, you need add something in your front end forms like this:
<?php wp_nonce_field(‘tomas_insert_messagebox’); ?>
This will generate codes like this automatically:
<input type=”hidden” id=”_wpnonce” name=”_wpnonce” value=”619dea88b4″>
2: In your server end, you need use function check_admin_referer in your $_POST process section, like this:
check_admin_referer( ‘tomas_insert_messagebox’ );
insert to your database;
your other codes;
the function check_admin_referer() will verify the nonce and if the data submitted from front end is not safe, check_admin_referer() will call wp_nonce_ays(), in the function wp_nonce_ays(), wp will detect your action, for example if you are try to log out from your site, WP will show a white panel and tell you “You are attempting to log out of Tomas Zhu“? Or something like ‘Are you sure you want to do this?’ and so on, finally, wordpress will return 403 with “WordPress Failure Notice”.
So it is very easy, right? Any more question please comment, I am happy to discuss with your. 🙂
Thanks dears, have a great day with your family. 🙂