Halloween Sale 15% off Ends in See the plans
PHP

Reject Gravity Forms Submitted Too Quickly

Adds a signed time stamp to each Gravity Forms form and marks entries sent within a few seconds of the page loading as spam, which catches bots that fill forms instantly.

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

Code

$wpide_gf_min_seconds = 4; // Minimum seconds between page load and submit.

add_filter( 'gform_form_tag', function ( $tag, $form ) {
    $time = (string) time();
    $tag .= '<input type="hidden" name="wpide_gf_ts" value="' . esc_attr( $time . '.' . wp_hash( 'gf-ts-' . $time ) ) . '">';

    return $tag;
}, 10, 2 );

add_filter( 'gform_entry_is_spam', function ( $is_spam, $form, $entry ) use ( $wpide_gf_min_seconds ) {
    if ( $is_spam ) {
        return $is_spam;
    }

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

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

    if ( method_exists( 'GFCommon', 'set_spam_filter' ) ) {
        GFCommon::set_spam_filter( rgar( $form, 'id' ), 'WPIDE time trap', $valid ? 'Submitted too quickly.' : 'Missing time stamp.' );
    }

    return true;
}, 10, 3 );

Notes

Safe with page caching because older stamps always pass; multi-page forms keep the first stamp.

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.