How to Block IP Addresses From Completing Your Form

Introduction

Would you like to block IP addresses from completing your form? You can easily block users from completing your form with the WPForms Allow/Deny list, but did you know that you can also block them just based on their IP Address? In this tutorial, we’ll show you how to use a small PHP snippet to achieve this.

For further information on creating an Allow/Deny list, please review this tutorial.

Creating the form

First, create your form and add your fields to this form. If you need any help in creating your form, please check out this documentation.

begin by creating your form and adding your fields

Adding the snippet

Once the form is created and published, you can now add this snippet to your site.

If you’re not sure how or where to add snippets to your site, please review this tutorial.

/**
 * Block form submissions based on IP address
 *
 * @link   https://wpforms.com/developers/how-to-block-ip-addresses-from-completing-your-form/
 */
function wpf_ip_block( $fields, $entry, $form_data ) {
      
    // Get the current users IP address
    $ip_address = wpforms_get_ip();

    // List out the IP addresses separated by a comma
    $blocked_ips = array(
        '129.222.6.90',
        '127.0.0.1',
    );
      
    // Check if the current user IP address is a blocked IP
    if ( in_array( $ip_address, $blocked_ips ) ) {
		
        // Block form submission and print error
        wpforms()->process->errors[ $form_data[ 'id' ] ] [ 'footer' ] = esc_html__( 'Your IP address has been blocked. Please contact the site administrator for further assistance.', 'text-domain' );
    }
}
add_action( 'wpforms_process', 'wpf_ip_block', 10, 3 );

This snippet will first find the user’s IP address and if it matches the list of blocked IP addresses, the form will not submit and an error will be displayed.

with this snippet you can now block IP addresses

And that’s all you need to block IP addresses from submitting to any of your WPFForms. Would you like to also block form submissions by name? Check out our tutorial on How to Block Names From Completing Your Form.

Action Reference: wpforms_process