Halloween Sale 15% off Ends in See the plans
PHP

Reject Contact Form 7 Submissions Sent Too Fast

Stamps each Contact Form 7 form with a signed time when it is shown and treats submissions sent within a few seconds as spam. People take longer than bots to fill in a form.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_cf7_min_seconds = 4; // Minimum time between showing the form and submitting it.

add_filter( 'wpcf7_form_hidden_fields', function ( $fields ) {
    $time = (string) time();
    $fields['wpide_cf7_ts'] = $time . '.' . wp_hash( 'cf7-ts-' . $time );

    return $fields;
} );

add_filter( 'wpcf7_spam', function ( $spam, $submission = null ) use ( $wpide_cf7_min_seconds ) {
    if ( $spam ) {
        return $spam;
    }

    $stamp = isset( $_POST['wpide_cf7_ts'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_cf7_ts'] ) ) : '';
    $parts = explode( '.', $stamp, 2 );
    $valid = 2 === count( $parts ) && ctype_digit( $parts[0] ) && hash_equals( wp_hash( 'cf7-ts-' . $parts[0] ), $parts[1] );

    if ( $valid && time() - (int) $parts[0] >= $wpide_cf7_min_seconds ) {
        return false;
    }

    if ( $submission && method_exists( $submission, 'add_spam_log' ) ) {
        $submission->add_spam_log( array( 'agent' => 'wpide-time-trap', 'reason' => $valid ? 'Submitted too quickly.' : 'Missing or forged time stamp.' ) );
    }

    return true;
}, 10, 2 );

Notes

Works with page caching because older stamps always pass; raise the seconds for long forms if you see false positives in the spam log.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.