WordPress Bloated “session_token” in MySQL Database

I’m running a wordpress site on a vps. My site has too many users using the wordpress login, so every couple of days the site login form stop working and keeps redirecting the user to the login form again and again (not to the dashboard). After investigation and trying to figure out whats going on i logged into phpmyadmin and found out that the “session_tokens” field in “wp_usermeta” was getting bloated (i.e. too many connections/idle connections). I just cleared all values and everything started to work.

Now i’m looking for a way to clear that field from mysql db every 12 hour. I looked up WordPress code reference (
https://developer.wordpress.org/reference/classes/wp_session_tokens/destroy_all_for_all_users/) and found a function that destroy all session tokens for all users.

Read More
final public static function destroy_all_for_all_users() {
    $manager = apply_filters( 'session_token_manager', 'WP_User_Meta_Session_Tokens' );
    call_user_func( array( $manager, 'drop_sessions' ) );
}

If there is a way to create a simple php file that i could run every time to clear this will be great (I can then create a cron job), but I’m not sure if that’s possible or how it can be done. Any help is appreciated.

Thanks.

P.s.I did try a plugin to logout idle connections, but that didn’t help at all.

Related posts

2 comments

  1. WordPress has the ability to schedule cron tasks built in, since there’s a WordPress method to clean the sessions out it would make sense to use WordPress to schedule it as well.

    https://codex.wordpress.org/Function_Reference/wp_schedule_event

    The syntax of the function is:

    <?php wp_schedule_event(time(), 'hourly', 'my_schedule_hook', $args); ?>
    

    The method you need to call to clear your session data is:

    WP_Session_Tokens::destroy_all_for_all_users();
    

    Create a function with the logic inside and pass it into wp_schedule_Event along with when you want it to begin, how often you want it to occur and whatever other arguments you need.

  2. An untested event as demonstration:

    create event `evtDeleteSessionTokens`
        on schedule
            every 12 hour
        on completion preserve
        enable
        comment 'delete stale tokens every x hours'
        do begin
            delete from wp_usermeta where meta_key = 'session_tokens';
    end
    

Comments are closed.