Using WordPress ‘auth_cookie_expired’ PHP action

The auth_cookie_expired WordPress PHP action fires once an authentication cookie has expired.

Usage

add_action('auth_cookie_expired', 'your_custom_function', 10, 1);

function your_custom_function($cookie_elements) {
    // your custom code here
}

Parameters

  • $cookie_elements (string[]): Authentication cookie components. None of the components should be assumed to be valid as they come directly from a client-provided cookie value.
    • username (string): User’s username.
    • expiration (string): The time the cookie expires as a UNIX timestamp.
    • token (string): User’s session token used.
    • hmac (string): The security hash for the cookie.
    • scheme (string): The cookie scheme to use.

More information

See WordPress Developer Resources: auth_cookie_expired

Examples

Log expired authentication cookies

Log expired authentication cookies for debugging purposes.

add_action('auth_cookie_expired', 'log_expired_auth_cookie', 10, 1);

function log_expired_auth_cookie($cookie_elements) {
    error_log('Expired auth cookie: ' . print_r($cookie_elements, true));
}

Redirect user to custom login page

Redirect users to a custom login page when their authentication cookie expires.

add_action('auth_cookie_expired', 'redirect_to_custom_login_page', 10, 1);

function redirect_to_custom_login_page($cookie_elements) {
    wp_redirect('/custom-login-page');
    exit;
}

Send an email to the admin when a user’s authentication cookie expires.

add_action('auth_cookie_expired', 'notify_admin_auth_cookie_expired', 10, 1);

function notify_admin_auth_cookie_expired($cookie_elements) {
    $admin_email = get_option('admin_email');
    $subject = 'User auth cookie expired';
    $message = 'User: ' . $cookie_elements['username'] . ' - Auth cookie expired.';
    wp_mail($admin_email, $subject, $message);
}

Invalidate user session tokens when their authentication cookie expires.

add_action('auth_cookie_expired', 'invalidate_session_tokens', 10, 1);

function invalidate_session_tokens($cookie_elements) {
    $user = get_user_by('login', $cookie_elements['username']);
    if ($user) {
        $session_tokens = get_user_meta($user->ID, 'session_tokens', true);
        foreach ($session_tokens as $token => $session) {
            if ($session['expiration'] <= time()) {
                wp_destroy_current_sessions();
            }
        }
    }
}

Extend the expiration time of authentication cookies when they expire.

add_action('auth_cookie_expired', 'extend_auth_cookie_expiration', 10, 1);

function extend_auth_cookie_expiration($cookie_elements) {
    $user = get_user_by('login', $cookie_elements['username']);
    if ($user) {
        wp_set_auth_cookie($user->ID, false, $cookie_elements['scheme']);
    }
}