Halloween Sale 15% off Ends in See the plans
PHP

Block IP Addresses and Ranges

Denies access to the whole site for the IP addresses and IPv4 ranges you list, for example a persistent spammer or attacker.

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

Code

// Single addresses (IPv4 or IPv6) or IPv4 ranges in CIDR form.
$wpide_blocked_ips = array( '192.0.2.10', '198.51.100.0/24' );

$wpide_visitor_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : '';

if ( $wpide_visitor_ip && ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
    foreach ( $wpide_blocked_ips as $wpide_entry ) {
        $wpide_match = false;

        if ( false === strpos( $wpide_entry, '/' ) ) {
            $wpide_match = ( $wpide_visitor_ip === $wpide_entry );
        } elseif ( filter_var( $wpide_visitor_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
            list( $wpide_subnet, $wpide_bits ) = explode( '/', $wpide_entry, 2 );
            $wpide_mask  = -1 << ( 32 - (int) $wpide_bits );
            $wpide_match = ( ip2long( $wpide_visitor_ip ) & $wpide_mask ) === ( ip2long( $wpide_subnet ) & $wpide_mask );
        }

        if ( $wpide_match ) {
            status_header( 403 );
            header( 'Content-Type: text/plain; charset=utf-8' );
            exit( 'Access denied.' );
        }
    }
}

Notes

Behind Cloudflare or another proxy, REMOTE_ADDR is the proxy; configure your server to pass the real visitor IP first.

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.