# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, sessions, cookies
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/end-sessions-on-ip-change/

## Code

```php
// '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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "End Admin Sessions When the IP Address Changes" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
