I've read the reference of this function on Wordpress but i still don't understand what this function really does.
I'm reading a tutorial about creating a meta box in wordpress and I have this code inside the function which saves the data:
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
Can someone explain briefly what is the meaning of wp_verify_nonce() ?
The nonce is a 'number used once' - a code that WP uses to make sure that POST data is coming from a safe place. This is useful to make sure that your plugin does not end up digesting data from an unsafe source (see Cross-Site Request Forgery).
This blog post by Mark Jaquith is useful for understanding them.
[nonces] are unique to the WordPress install, to the WordPress user, to the action, to the object of the action, and to the time of the action (24 hour window). That means that if any of these things changes, the nonce is invalid. So if you (somehow) intercept a nonce being used by me, you would, first of all, only have 24 hours to use this key to attempt to trick me.
To create a nonce you must give wp_create_nonce
a certain string, providing the 'context' for the nonce. It gives you back a string - the nonce itself. You then include this nonce as part of your POST request. The receiving page should then create a nonce of its own, using the same context, and see if they match up.
In this case, the context given is plugin_basename(__FILE__)
. This will generate the same string whenever it is called from within the same plugin (see here).
When your wp_verify_nonce
recieves a nonce created under the same circumstances as specified by Mark, with the same context string, it returns true.
In short:
!wp_verify_nonce
returns true if wp_verify_nonce returns false.
($_POST[$meta_box['name'].'_noncename'],
First argument to wp_verify_nonce
: the nonce to check. This code gets the nonce out of the post request, stored in the $_POST global.
plugin_basename(__FILE__) )
Second argument to wp_verify_nonce
: the context for generating the new nonce against which the first will be checked.
{ return $post_id; }
If the nonce doesn't match, stop executing the current function, returning the variable $post_id
.