# Block Fake Googlebot Visits

> Checks visitors that claim to be Googlebot with a reverse DNS lookup and blocks the impostors, which are usually scrapers or vulnerability scanners.

- Type: PHP
- Runs: Frontend only
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, bots, dns
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/block-fake-googlebot/

## Code

```php
add_action( 'init', function () {
    $agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
    $ip    = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : '';

    if ( false === stripos( $agent, 'Googlebot' ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
        return;
    }

    $key     = 'wpide_gbot_' . md5( $ip );
    $genuine = get_transient( $key );

    if ( false === $genuine ) {
        $host    = gethostbyaddr( $ip );
        $forward = array();

        if ( $host && preg_match( '/\.(googlebot|google)\.com$/i', $host ) ) {
            if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
                $forward = (array) gethostbynamel( $host );
            } else {
                foreach ( (array) dns_get_record( $host, DNS_AAAA ) as $record ) {
                    if ( ! empty( $record['ipv6'] ) ) {
                        $forward[] = inet_ntop( inet_pton( $record['ipv6'] ) );
                    }
                }
                $ip = inet_ntop( inet_pton( $ip ) );
            }
        }

        $genuine = in_array( $ip, $forward, true ) ? 'yes' : 'no';
        set_transient( $key, $genuine, DAY_IN_SECONDS );
    }

    if ( 'no' === $genuine ) {
        status_header( 403 );
        exit( 'Forbidden' );
    }
}, 0 );
```

## Notes

The DNS check runs once per IP per day and adds a short delay to that first request.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block Fake Googlebot Visits" 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/
