Is there a way to correctly use sanitize_text_field and wp_unslash that doesn't cause psalm to error

I am writing a WordPress plugin, and need to correctly unslash and sanitise a variable in PHP. I am using psalm as my static analysis tool, and it is identifying my code as containing a potential error:

I am writing a WordPress plugin, and need to correctly unslash and sanitise a variable in PHP. I am using psalm as my static analysis tool, and it is identifying my code as containing a potential error:

// Check your nonce. if ( isset( $_POST['_wpnonce'] ) ) { if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) ) ) { // other code here } } 

Psalm shows this an an error (or warning, depending on the psalm level I set):

Argument 1 of sanitize_text_field expects string, possibly different type array<array-key, mixed>|string provided 

I have tried various other ways of arranging the code above to prevent psalm from not presenting this warning, but I am unable to. (Yes, I am a aware that the reason the message is being displayed is because wp_unslash can return an string or an array).

For example, if I split the code up:

// Check your nonce. if ( isset( $_POST['_wpnonce'] ) ) { $unslashed = wp_unslash( $_POST['_wpnonce'] ); $sanitized = sanitize_text_field( $unslashed ); if ( ! wp_verify_nonce( $sanitized ) ) { // other code here } } 

I then get the following psalm error:

Detected usage of a non-sanitized input variable: $_POST['_wpnonce'] 

Is there a way to arrange this code (without supressing the message) that will keep psalm happy, and also keep inline with the WordPress Coding Standards (e.g. you should unslash before you sanitize)?

4

1 Answer

You can use sanitize_key() to sanitize WP nonce. The following gets passed in WPCS

if ( isset( $_POST['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ) ) ) { echo 'hi'; } 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmluY2mDenyOoqpmrJiav6Z5wGaumrFdqbxur86rqZ6bpKHGbsHSnmSsmZ6ewarGxGarnrCkYrOqscudZJqmlGLEsXnUp6qlmaOderW0wK1knaeVqLu1

ncG1vNJzZmilpZ6%2Fb63MrGpnnJmctrWty6ianpmeqL2ir8SsZZynnWS2tHnToZyrnV2Werit2GarqGWTpL%2BzscKto7Jlpaiybr%2FAp6CtoaqaerWx161kn6GVobFurc2dZLCoXaq7tLjArJ9mrJiWwW6wzp6qp2WkYrCiwdKeZKmrkaG6bsDOZpyrqp%2Bne6nAzKU%3D

 Share!