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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.