Security PHP Intermediate

Email Administrators When They Log In From a New IP

Send administrators an email when their account logs in from an IP address it hasn't used before.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 32 lines
add_action( 'wp_login', function ( string $login, WP_User $user ): void {
	if ( ! user_can( $user, 'manage_options' ) ) {
		return;
	}

	$ip    = sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' );
	$known = array_values( array_filter( (array) get_user_meta( $user->ID, 'nahnu_known_ips', true ) ) );

	if ( '' === $ip || in_array( $ip, $known, true ) ) {
		return;
	}

	$first_time = ! $known;
	$known[]    = $ip;
	update_user_meta( $user->ID, 'nahnu_known_ips', array_slice( $known, -10 ) );

	// The first login after adding the snippet only records the address.
	if ( $first_time ) {
		return;
	}

	wp_mail(
		$user->user_email,
		sprintf( '[%s] New login to your account', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
		sprintf(
			"Your administrator account just logged in from a new IP address.\n\nIP address: %s\nBrowser: %s\nTime: %s\n\nIf this wasn't you, change your password now and check Users in wp-admin.",
			$ip,
			sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ?? 'unknown' ),
			wp_date( 'Y-m-d H:i T' )
		)
	);
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

If someone else logs in with an administrator’s password, the real owner should know straight away. This snippet emails administrators when their account signs in from an IP address it hasn’t used recently.

How it works

On wp_login, the snippet compares the IP address with the last ten addresses saved for that user. A known address does nothing. A new one is added to the list and triggers an email to the account owner with the address, browser and time.

The very first login after you add the snippet only records the address, so nobody gets an email just for installing it.

Things to watch

  • Mobile connections and some home internet providers change IP addresses often, which means more emails. That’s the trade-off for being alerted.
  • Behind Cloudflare or a proxy, have your host restore real visitor IPs, or every login will look like it comes from the same few addresses.

How to test it

Log in as an administrator, then log in again from a different network, such as your phone’s mobile data. You should receive the alert.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only