Accessing user input data

Posts in the developer's cookbook category describe topics that require technical knowledge. Be warned and use the techniques at your own risk. Unless you are an experienced developer, you are strongly advised to ask a professional for support.

To access user input posted through a contact form, you can refer to PHP’s native global variable $_POST. Besides this, Contact Form 7’s WPCF7_Submission class provides a different data source ($posted_data) that can be used to access user input. What are the differences between $_POST and $posted_data? And which one should you use for your purpose?

$_POST includes raw data that the user has posted. $posted_data includes data that are sanitized and processed for use by Contact Form 7.

While $_POST includes all posted data, some that represent meta information of the submission (such as the ID of the contact form) and some that are irrelevant to the submitter’s intention (such as the answer to a CAPTCHA question) are excluded from $posted_data.

The following code snippet shows an example that retrieves user input from $posted_data.

add_action( 'wpcf7_before_send_mail',
  function( $contact_form, &$abort, $submission ) {
    // Getting user input through the your-email field
    $your_email = $submission->get_posted_data( 'your-email' );

    // Getting user input through the your-message field
    $your_message = $submission->get_posted_data( 'your-message' );

    // Do some productive things here
  10, 3

As you see in this example, you use the get_posted_data() method to access the data. You are not allowed to directly access the $posted_data property.

The value that get_posted_data() returns is a string or an array of string values. It is advised to treat the returned value as always assuming both cases, like in the following example:

$your_email = $submission->get_posted_data( 'your-email' );

// Cast to array and join the array elements with a comma.
$your_email = implode( ', ', (array) $your_email );

Don’t use $posted_data for validation or spam-filtering.

Don’t use $posted_data for input validation or spam-filtering. Use $_POST instead, because those tasks make sense only when done against raw user input data.