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

CodeIgniter登录验证异常:正确用户名搭配任意密码均可登录

问题排查与解决方案

核心问题定位

当前登录逻辑的关键问题出在$this->Mcustomer->customer_login($username, $password)模型方法上——该方法大概率未同时校验用户名和密码,仅根据用户名查询用户数据,导致只要用户名正确,无论密码是否匹配都会返回用户信息,触发登录成功流程。

具体修复步骤

1. 修正Mcustomer模型的customer_login方法

打开application/models/Mcustomer.php,检查并修改customer_login方法:

  • 错误示例(仅校验用户名):
public function customer_login($username, $password) {
    $this->db->where('username', $username);
    return $this->db->get('customers')->row_array();
}
  • 正确实现(同时校验用户名和密码):
public function customer_login($username, $password) {
    $this->db->where('username', $username);
    $this->db->where('password', $password); // 需确保数据库密码为MD5加密存储
    $query = $this->db->get('customers');
    return $query->num_rows() === 1 ? $query->row_array() : FALSE;
}

2. 优化控制器代码冗余

当前控制器两次调用模型方法,可优化为单次查询,同时建议使用CodeIgniter原生input类替代$_POST:

public function dangnhap(){
    $this->load->library('form_validation');
    $this->form_validation->set_rules('username', 'Tài khoản', 'required|min_length[6]|max_length[32]');
    $this->form_validation->set_rules('password', 'Mật khẩu', 'required|min_length[6]|max_length[32]');
    
    if($this->form_validation->run() == TRUE){
        $username = $this->input->post('username');
        $password = md5($this->input->post('password'));
        
        // 单次调用模型方法
        $row = $this->Mcustomer->customer_login($username, $password);
        if($row !== FALSE){
            $this->session->set_userdata('sessionKhachHang',$row);
            $this->session->set_userdata('id',$row['id']);
            $this->session->set_userdata('email',$row['email']);
            $this->session->set_userdata('sessionKhachHang_name',$row['fullname']);
            
            redirect($this->session->userdata('cart') ? 'gio-hang' : 'thong-tin-khach-hang', 'refresh');
        }else{
            $this->data['error']='Tài khoản hoặc mật khẩu không chính xác';
            $this->data['title']='Đăng nhập tài khoản';
            $this->data['view']='dangnhap';
            $this->load->view('frontend/layout',$this->data);
        }
    }else{
        $this->data['title']='Smart store - Đăng nhập tài khoản';
        $this->data['view']='dangnhap';
        $this->load->view('frontend/layout',$this->data);
    }     
}

3. 安全优化建议

MD5加密安全性较低,建议改用PHP原生的password_hash()和password_verify():

  • 注册时加密密码:
$hashed_password = password_hash($raw_password, PASSWORD_DEFAULT);
  • 登录时校验逻辑:
public function customer_login($username, $password) {
    $this->db->where('username', $username);
    $user = $this->db->get('customers')->row_array();
    return $user && password_verify($password, $user['password']) ? $user : FALSE;
}

内容的提问来源于stack exchange,提问作者Võ Trường

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:05:22