# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, ip, blocklist
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/block-ip-addresses/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block IP Addresses and Ranges" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
