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

CodeIgniter中登录错误消息验证问题排查

Fixing Login Error Messages for Empty Username/Password in CodeIgniter

Let's walk through the issues in your current code and fix them step by step to get the proper error messages showing when users skip entering username or password.

Key Issues in Your Current Implementation

  1. Form Validation Rules Are Disabled: You've commented out the critical set_rules calls, so CodeIgniter isn't checking for required fields at all.
  2. Syntax Error in Validation Rules: The extra 'required' parameter at the end of your set_rules lines is invalid.
  3. Flashdata Overwrite: You're setting two flash messages, but the second one replaces the first, so you'll never see the "Username Not Entered" message.
  4. SQL Injection Risk: Your model uses string concatenation for the database query, which is unsafe.

Step 1: Fix the Controller Code

Uncomment and correct the form validation rules, and adjust the error handling flow:

public function login_user() {
    // Fix validation rules (remove the extra 'required' parameter)
    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

    if ($this->form_validation->run() == FALSE) {
        // Validation failed (empty fields), reload login view
        $this->load->view('login_view');
    } else {
        $data = array(
            'username' => $this->input->post('username'),
            'password' => $this->input->post('password'),
            'firstname' => $this->input->post('firstname'),
            'lastname' => $this->input->post('lastname')
        );

        $result = $this->login_database->login($data);
        if ($result == TRUE) {
            // Add user data in session
            $this->session->set_userdata('username', $data['username']);
            $this->session->set_userdata('firstname', $data['firstname']);
            $this->session->set_userdata('lastname', $data['lastname']);

            // Redirect to dashboard (better to use redirect() instead of loading views directly)
            redirect('dashboard');
        } else {
            // Invalid credentials (username/password mismatch)
            $this->session->set_flashdata('err_message', 'Login is invalid. Please try again !');
            $this->load->view('login_view', $data);
        }
    }
}

Note: Using redirect() instead of loading views directly after setting session data helps avoid issues with page reloads.


Step 2: Secure the Model Code

Replace the unsafe string concatenation with parameter binding to prevent SQL injection:

public function login($data) {
    $this->db->select('*');
    $this->db->from('users');
    // Use array for where clause (CodeIgniter handles escaping automatically)
    $this->db->where(array(
        'username' => $data['username'],
        'password' => $data['password']
    ));
    $this->db->limit(1);

    $query = $this->db->get();
    return $query->num_rows() == 1;
}

Step 3: Update the View to Show Validation Errors

Modify your login view to display both form validation errors (for empty fields) and flash messages (for invalid credentials):

<!-- Show form validation errors for required fields -->
<?php echo validation_errors('<div class="error">', '</div>'); ?>

<!-- Show flash message for invalid login -->
<?php if( $this->session->flashdata('err_message') ) { ?>
    <div class="error"><?php echo $this->session->flashdata('err_message'); ?></div>
<?php } ?>

<!-- Your login form goes here -->
<form method="post" action="<?php echo site_url('controller_name/login_user'); ?>">
    <label>Username:</label>
    <input type="text" name="username" value="<?php echo set_value('username'); ?>">
    
    <label>Password:</label>
    <input type="password" name="password">
    
    <button type="submit">Login</button>
</form>

The validation_errors() function will automatically show messages like "The Username field is required" when users submit empty fields. The set_value() function retains the entered username if validation fails, improving user experience.


How It Works Now

  1. If the user submits an empty username or password, the form validation fails immediately, and the view shows the required field errors.
  2. If the user enters both fields but the credentials are wrong, the flash message "Login is invalid..." is displayed.
  3. The model query is now safe from SQL injection.

内容的提问来源于stack exchange,提问作者suresh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:51:17