Question

i dont really understand why the check if the nonce function exists before running it ...

if ( function_exists('wp_nonce_field') ) 
     wp_nonce_field('gmp_nonce_check');

i understand its for backwards compatibility ...

Also notice how you are verifying that the wp_nonce_field function exists before trying to call it for backward compatibility

but wont it break anyway if on post back i check

if ( isset($_POST['submit']) ) {
     check_admin_referer('gmp_nonce_check');
Was it helpful?

Solution

The answer is that you should not check if wp_nonce_field() exists before using it!

The recommendation to perform the check assumes that you want to be compatible with versions of WordPress from before the function existed. If Rarst is right that it was introduced in 2.0.4 then you should NOT be supporting earlier versions, as they are all absolutely insecure and anyone using them needs to upgrade RIGHT NOW.

Usually you should not have to check for existence of functions from inside WP, unlike functions from plugins that might not be activated.

Where did you see that comment you quoted? It should be removed.

OTHER TIPS

If I understand your question right - you ask why there is no need to check if check_admin_referer() defined as well?

As far as I see from docs this function is much older (since WP 1.2.0) than wp_nonce_field() (since WP 2.0.4). So I would assume you are much less likely to encounter version that ancient that it doesn't have check_admin_referer().

You check for the existence of a function to prevent a fatal error and subsequent application halt when your code is executed on a version of WordPress that does not include the function you are attempting to use.

Does this ensure backwards compatibility? Absolutely. More importantly, however, this check prevents your code from causing the entire application to crash when your code is executed:

Error handling should be “graceful” in any system – meaning that the application should know how to detect its own errors and handle them in some appropriate manner with minimal interruption for end users. Read more at http://www.devshed.com/c/a/PHP/PHP-Application-Development-Part-Two/2/#wIxuV7yhLhBTU1UZ.99

Thus, in your code, you could do the following:

if ( function_exists('wp_nonce_field') ) {
 wp_nonce_field('gmp_nonce_check');
} else {
 //do nothing
 exit() ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top