You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于现有CodeIgniter 4登录代码实现用户与管理员分页面跳转?

CodeIgniter 4 按用户角色跳转登录页面实现方案

前置准备

先确认你的users数据表中包含标识用户角色的字段,比如命名为role,字段类型建议用VARCHAR,取值可以设为user(普通用户)、admin(管理员),可根据实际业务调整。

修改后的登录验证代码

public function loginAuth()
{
    $session = session();
    $userModel = new UserModel();
    $email = $this->request->getVar('email');
    $password = $this->request->getVar('password');
    $data = $userModel->where('email', $email)->first();
    
    if($data)
    {
        $pass = $data['password'];
        $authenticatePassword = password_verify($password, $pass);
        
        if($authenticatePassword)
        {
            $ses_data = [
                'id' => $data['id'],
                'name' => $data['name'],
                'email' => $data['email'],
                'role' => $data['role'], // 新增角色字段到session
                'isLoggedIn' => TRUE
            ];
            $session->set($ses_data);
            
            // 根据角色判断跳转目标
            if($data['role'] === 'admin'){
                return redirect()->to('/admin');
            } else {
                return redirect()->to('/profile');
            }
        }else{
            $session->setFlashdata('msg', 'Password is incorrect.');
            return redirect()->to('/signin');
        }
    }else{
        $session->setFlashdata('msg', 'Email does not exist.');
        return redirect()->to('/signin');
    }
}

关键改动说明

  • 把用户角色存入session,后续页面做权限验证时可直接调用$session->get('role')判断
  • 将固定跳转/profile改为条件分支,根据用户角色跳转到对应页面,管理员跳/admin,普通用户保持跳/profile
  • 如果你的角色字段名不是role,或者跳转路径不同,直接替换对应值即可

内容的提问来源于stack exchange,提问作者Rachel Ann Labre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:45:34