duanlao6573 2017-12-06 09:21
浏览 81

销毁除最后两个之外的其他登录Wordpress会话

I'm trying to add a function to the wp_login hook which scans all current user login sessions, and destroy all, except the last two (which contains current session). I'm want user to be logged in on max. two devices simultaneously.

I can fetch the sessions with:

$manager = WP_User_Meta_Session_Tokens::get_instance( $user->ID );
$tokens = $manager->get_all();

or:

$tokens = get_user_meta($user->ID, 'session_tokens', true);

But how can you destroy these sessions during a for loop?

foreach($tokens as $token){
  $manager->destroy( $token );
}

returns: hash() expects parameter 2 to be string. Using the keys as value doesn't work either.

  • 写回答

1条回答 默认 最新

  • douye5949 2017-12-06 14:36
    关注

    I used a different approach for now, updating the user_meta directly did the trick

    function limit_active_user_sessions( $user_login, $user ){
    
     $sessions = get_user_meta( $user->ID, 'session_tokens', true );
     $sessions_keys = array_keys($sessions);
     $sessions_count = count($sessions);
     $max_active_sessions = 2;
     if ( $sessions_count > 2 ){
      for($i=0;$i<($sessions_count-$max_active_sessions);$i++){ 
       unset( $sessions[$sessions_keys[$i]] );
      }
      update_user_meta( $user->ID, 'session_tokens', $sessions );
     }
    
    add_action( 'wp_login', 'limit_active_user_sessions', 10, 2 );
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?