In WordPress plugin development, nonces are often used. What is their main purpose?
Think about how plugins protect actions triggered by users from outside attackers.
Nonces in WordPress are security tokens that help verify requests are intentional and from trusted users, preventing Cross-Site Request Forgery (CSRF) attacks.
Consider a WordPress plugin form that processes user input but does not verify the nonce. What is the likely outcome?
Think about what nonce verification protects against and what happens if it is missing.
Without nonce verification, attackers can trick logged-in users into submitting forms unknowingly, leading to unauthorized actions.
Choose the code snippet that properly checks a nonce named 'my_nonce' sent via POST before processing the form.
<?php if (/* your code here */) { wp_die('Security check failed'); } else { // process form } ?>
Remember to check if the nonce exists and that verification returns true.
Option A correctly checks if the nonce is set and verifies it returns true. The condition negates this to stop processing if verification fails.
Review this code snippet from a WordPress plugin:
<?php
$user_input = $_POST['user_data'];
$clean_input = sanitize_text_field($user_input);
update_option('my_option', $user_input);
?>Why is the sanitization ineffective?
Check which variable is saved to the database.
The code sanitizes $user_input into $clean_input but saves the original unsanitized $user_input, making sanitization ineffective.
Given the following code snippet, what will be the output if the nonce is invalid and the user input is <script>alert('x')</script>?
<?php if ( ! isset($_POST['my_nonce']) || ! wp_verify_nonce($_POST['my_nonce'], 'my_action') ) { echo 'Nonce verification failed'; exit; } $input = sanitize_text_field($_POST['user_input']); echo 'User input: ' . $input; ?>
Consider what happens when nonce verification fails.
If the nonce is missing or invalid, the code echoes 'Nonce verification failed' and stops execution before sanitizing or echoing user input.