End Admin Sessions When the IP Address Changes
Logs an administrator out if their session suddenly comes from a different IP address than the one they logged in from, which blocks stolen cookies.
Opens WPIDE on
Code
// 'subnet' tolerates changes inside the same /24 (IPv4) or /64 (IPv6) network; 'exact' requires the same IP.
$wpide_ip_match = 'subnet';
$wpide_ip_prefix = function ( $ip ) use ( $wpide_ip_match ) {
if ( 'exact' === $wpide_ip_match ) {
return $ip;
}
if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
return implode( '.', array_slice( explode( '.', $ip ), 0, 3 ) );
}
if ( ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
return $ip;
}
return bin2hex( substr( inet_pton( $ip ), 0, 8 ) );
};
add_action( 'init', function () use ( $wpide_ip_prefix ) {
if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) || empty( $_SERVER['REMOTE_ADDR'] ) ) {
return;
}
$token = wp_get_session_token();
$manager = WP_Session_Tokens::get_instance( get_current_user_id() );
$session = $token ? $manager->get( $token ) : null;
if ( empty( $session['ip'] ) ) {
return;
}
if ( $wpide_ip_prefix( $session['ip'] ) !== $wpide_ip_prefix( (string) $_SERVER['REMOTE_ADDR'] ) ) {
$manager->destroy( $token );
wp_clear_auth_cookie();
wp_safe_redirect( wp_login_url() );
exit;
}
}, 1 );
Notes
Mobile and some office networks change IP often; switch to subnet matching or remove the snippet if admins get logged out too much.
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.