Last active
April 17, 2020 22:09
-
-
Save lkoudal/997fe76da8f30faa703ea13f8c468f74 to your computer and use it in GitHub Desktop.
Check and verify a nonce in WordPress plugin from JavaScript code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('wp_ajax_get_custom_data', 'get_custom_data'); | |
function get_custom_data() { | |
// Ready for the magic to protect your code? | |
check_ajax_referer('secure-plugin-nonce'); | |
/* That's it - the check_ajax_referer function verifies the nonce is correct or it dies and stops code execution if it fails. | |
If you want to customize the error handling and perhaps return an error to your JS code, you could change the code to something like: | |
if ( ! check_ajax_referer( 'secure-plugin-nonce', false, false ) ) { | |
wp_send_json_error( 'Invalid nonce' ); | |
} | |
*/ | |
$sanitized_user_data = sanitize_text_field( $_POST['user_data'] ); | |
// ... continue with the rest of your plugin code ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment