Halloween Sale 15% off Ends in See the plans
PHP

Ban IPs That Try Common Attack Usernames

Blocks an IP address from logging in for a day as soon as it tries a username like "admin" or "test" that does not exist on your site.

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

Code

// Usernames that only bots try (they must not exist on your site).
$wpide_trap_usernames = array( 'admin', 'administrator', 'root', 'test', 'user', 'demo', 'wordpress', 'wp' );
$wpide_trap_ban_time  = DAY_IN_SECONDS;

$wpide_trap_key = function () {
    $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : 'unknown';

    return 'wpide_trap_' . md5( $ip );
};

add_action( 'wp_login_failed', function ( $username ) use ( $wpide_trap_usernames, $wpide_trap_ban_time, $wpide_trap_key ) {
    $username = strtolower( trim( (string) $username ) );

    if ( in_array( $username, $wpide_trap_usernames, true ) && ! username_exists( $username ) ) {
        set_transient( $wpide_trap_key(), 1, $wpide_trap_ban_time );
    }
} );

add_filter( 'authenticate', function ( $user ) use ( $wpide_trap_key ) {
    if ( get_transient( $wpide_trap_key() ) ) {
        return new WP_Error( 'wpide_trap_banned', '<strong>Error:</strong> Login is temporarily blocked from your network.' );
    }

    return $user;
}, 1 );

Notes

Never list a username that a real person on your site uses.

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.