7

The general guideline is that we should sanitize all user input before using them.

Now my questions is whether this applies to nonce or not.

Which one is correct?

wp_verify_nonce( sanitize_text_field( $_GET['some_nonce'] ), 'some_nonce' );

or

wp_verify_nonce( _GET['some_nonce'], 'some_nonce' );

1
  • 2
    Relevant issue at github/WordPress/WordPress-Coding-Standards. TLDR: It's not necessary as explained by Fayaz below; but if your environment is throwing warnings because of the unsanitized $_REQUEST then use sanitize_key()
    – brasofilo
    Commented Jan 16, 2021 at 19:36

1 Answer 1

8

Sanitizing is required when you are inserting user input into Database or outputting it in HTML etc. Here, you are simply doing a String comparison.

wp_verify_nonce function checks $nonce value like this:

if ( hash_equals( $expected, $nonce ) ) {
    return 1;
}

For this you don't need sanitizing. So the following is fine:

wp_verify_nonce( $_GET['some_nonce'], 'some_nonce' );

Note: If it generates any warning for Plugin development or any other code standard, use the sanitize_key function to avoid the warning, but technically it shouldn't be needed for security:

wp_verify_nonce( sanitize_key( $_GET['some_nonce'] ), 'some_nonce' );

5
  • 2
    Note that this should check isset( $_GET['some_nonce'] ) first to avoid an error if the query string arg is not there.
    – butlerblog
    Commented Dec 27, 2022 at 13:23
  • If you're building a WP plugin, you will be asked to sanitze any and all POST/GET/REQUEST - not just what goes into the database
    – Philip
    Commented Dec 15, 2023 at 21:59
  • @butlerblog of course, that's a given. But I didn't include that in the answer because the question was specific to nonce sanitization.
    – Fayaz
    Commented Dec 16, 2023 at 2:00
  • @Philip I was referring to the original reasoning behind Sanitizing, not what is expected in any code standard. Code standards change over time, original logic doesn't. You'll find a more detailed related discussion here: github.com/WordPress/WordPress-Coding-Standards/issues/869
    – Fayaz
    Commented Dec 16, 2023 at 2:25
  • 1
    @Philip Also, you can see here that the core itself doesn't do nonce sanitization: github.com/WordPress/wordpress-develop/blob/6.2/src/wp-includes/…
    – Fayaz
    Commented Dec 16, 2023 at 2:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.