Halloween Sale 15% off Ends in See the plans
PHP

Email Users When They Log In From a New Device

Sends members an email when their account is used from a browser and network it has not seen before, so they can react quickly if it was not them.

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

Code

// How many known devices to remember per user.
$wpide_known_devices = 10;

add_action( 'wp_login', function ( $login, $user ) use ( $wpide_known_devices ) {
    $ip  = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
    $ua  = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
    // Use the network part of the IP so a changing last digit does not count as new.
    $net = preg_replace( '/\.\d+$/', '', $ip );
    $key = wp_hash( $net . '|' . $ua );

    $known = get_user_meta( $user->ID, 'wpide_known_devices', true );
    $first = ! is_array( $known );
    $known = $first ? array() : $known;

    if ( in_array( $key, $known, true ) ) {
        return;
    }

    array_unshift( $known, $key );
    update_user_meta( $user->ID, 'wpide_known_devices', array_slice( $known, 0, $wpide_known_devices ) );

    if ( $first ) {
        return;
    }

    wp_mail(
        $user->user_email,
        sprintf( '[%s] New login to your account', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
        sprintf(
            "Hi %s,\n\nYour account was just used to log in from a new device.\n\nTime: %s\nIP address: %s\nBrowser: %s\n\nIf this was you, there is nothing to do. If not, reset your password now:\n%s",
            $user->display_name,
            wp_date( 'Y-m-d H:i' ),
            $ip,
            $ua,
            wp_lostpassword_url()
        )
    );
}, 10, 2 );

Notes

The first login after activation is remembered without an email. Only a hash of the browser and network is stored, not the full IP address.

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.