In the introduction, I provided a brief overview of Numbers used ONCE (nonce) and how they are implemented in WordPress. In this part, I’ll introduce you to creating and verifying a nonce.
To get started with WordPress nonces, we need a plugin administration page. To make life easier for the budding developer, I’ve created a basic plugin called “WP Nonce Playground.” ('WP Nonce Playground: Part 1'). Upload and activate the plugin. Under “Settings” you will have a new tab: “WP Nonce”. On this screen you can set a check box and some text.
Unfortunately, this is not really secure, because it doesn’t check any credentials. Lets add some. To create a nonce, we’ll be using the wp_create_nonce($action) function. The $action parameter is optional, but without it the system is not nearly as secure. $action is a string, and you should create a unique $action for each different action which you will create
Open up wpn.admin.php. On line 61, add:
<input name="wpn-update_settings" type="hidden" value="<?php echo wp_create_nonce('wpn-update_setting'); ?>" />
This creates a hidden form field with the name wpn-update_settings and places a custom nonce in the value field. If you save the page, refresh, and examine the source, you’ll see the nonce in a hidden form field down at the bottom. Of course, we’re not actually checking it right now, so it’s not much use at the moment.
It’s easy enough to start checking the nonce, however. We use the companion to the wp_create_nonce($action) function, wp_verify_nonce($nonce, $action). Like wp_create_nonce, wp_verify_nonce does not explicitly require the $action parameter, however, whatever $action parameter was used to create the nonce must also be used for successful verification.
Back to wpn.admin.php. Replace lines 13 and 14 with:
if (!isset($_POST['wpn-update_settings'])) die("Hmm ..., looks like you didn't send any credentials"); if (!wp_verify_nonce($_POST['wpn-update_settings'],'wpn-update_settings')) die("Hmm ..., looks like you didn't send the right credentials");
Go ahead and save the page. Visit it and update the options.
Well, that didn’t work! If you copied and pasted exactly what I wrote above, you get the error:
Hmm …, looks like you didn’t send the right credentials
The eagle eyed among you will notice that on line 61, we created a nonce with the $action of ‘wp-update-setting’, but everywhere else, including in wp_verify_nonce, we used ‘wp-update-settings‘.
Update wpn.admin.php, line 61 to:
<input name="wpn-update_settings" type="hidden" value="<?php echo wp_create_nonce('wpn-update_settings'); ?>" />
Lo and behold, it works!
If your wpn.admin.php isn’t working, a working version with all the changes made in the part is also in the plugin folder at wpn.admin.final.php. You can rename this to wpn.admin.php to make the plugin work.
More:
- Part 0 — Background
- Part 1 — Basic Nonce Usage
Who's Lookin'
Thank you