Passing form data on submit

nrstx asked
forms security validation
via

In my sanitizing script, prior to using the POST Request method to submit this data, I have the following for my textarea input field named ‘contact_msg’:

if($_POST['contact_msg'] != ''){
      $contact_message = sanitize_textarea_field($_POST['contact_msg']);
      if(strlen($contact_message < 15)){
           $errors .= 'Please enter more information in your message.';
           $hasError = true;
      } elseif {strlen($contact_message > 2000)) {
           $errors .= 'Please shorten your message.';
           $hasError = true;
      }
 }

I’m a little tripped up because I don’t think the key/value pair for $_POST['contact_msg'] would be sanitized–only the variable, $contact_message which by default isn’t what is getting passed on submit, thus requiring me to do something else before passing the key/value pair for this input on submit? In other words, how do you actually sanitize $_POST['contact_msg']? Do you just add something like:

if($_POST['contact_msg'] != ''){
      $contact_message = sanitize_textarea_field($_POST['contact_msg']);
      if(strlen($contact_message < 15)){
           $errors .= 'Please enter more information in your message.';
           $hasError = true;
      } elseif (strlen($contact_message > 2000)) {
           $errors .= 'Please shorten your message.';
           $hasError = true;
      } else {
           $_POST['contact_msg'] = sanitize_textarea_field($_POST['contact_msg'];
      }

 }

in order to actually sanitize the data being posted?


Answer
via

First check that it’s not empty, then typecast to a string value as a security precaution, because it’s always possible for this to be submitted as an array; e.g., by an attacker. Then unslash, sanitize, and continue by checking length and anything else that you’d like to validate.

if ( ! empty( $_POST['contact_msg'] ) ){
    $contact_message = (string) $_POST['contact_msg'];
    $contact_message = wp_unslash( $contact_message );
    $contact_message = sanitize_textarea_field( $contact_message );
}

Tip: Also be sure to verify the request using an Nonce.


Here’s a more terse variation of the above.

if ( ! empty( $_POST['contact_msg'] ) ){
    $contact_message = sanitize_textarea_field( wp_unslash( (string) $_POST['contact_msg'] ) );
}
Share This
Posted in: