首页 > 解决方案 > Error message not shown when trying to login to an invalid username

问题描述

When I tried logging in to an invalid username, I got no error message. Instead it redirected to the same login page.

Here is the controller:

function cekuser()
{
    $username = strip_tags(stripslashes($this->input->post('username', TRUE)));
    $password = strip_tags(stripslashes($this->input->post('password', TRUE)));
    $u = $username;
    $p = md5($password);
    $cadmin = $this->Auth_model->check_login($u, $p);
    if (!$cadmin) {
        redirect('administrator/gagallogin');
    } else {
        if ($cadmin['level'] == '1') {
            $this->session->set_userdata('masuk', true);
            $this->session->set_userdata('user', $u);
            
            $this->session->set_userdata('akses', '1');
            $idadmin = $cadmin['id'];
            $user_nama = $cadmin['nama'];
            $this->session->set_userdata('idadmin', $idadmin);
            $this->session->set_userdata('nama', $user_nama);
        }
       
    }

    if ($this->session->userdata('masuk') == true) {
        redirect('administrator/berhasillogin');
    } else {
        redirect('administrator/gagallogin');
    }
}
function berhasillogin()
{
    redirect('dashboard');
}
function gagallogin()
{
    $url = base_url('administrator');
    echo $this->session->set_flashdata('msg', 'Username Atau Password Salah');
    redirect($url);
}

and here is for the login views:

 <form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">
  <label for="inputEmail" class="sr-only">NIP</label>
  <input class="form-control" type="text" name="username" placeholder="Username" required>
  <br />
  <label for="inputPassword" class="sr-only">Password</label>
  <input class="form-control" type="password" name="password" placeholder="Password" style="margin-bottom:1px;" required>
  <br />
  <br />
  <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>

Is there any solution? Thank you.

标签: phphtmlcodeigniter

解决方案


You don't echo the flash data, you just set it.

function gagallogin()
{
    $url = base_url('administrator');
    $this->session->set_flashdata('msg', 'Username Atau Password Salah');
    redirect($url);
}

In the form, you set the flash message with PHP. Change your form to a PHP file and do something like this:

  <?php if ($this->session->flashdata('msg') { ?>
  <p class="text-danger">Error: <?php echo $this->session->flashdata('msg'); ?></p>
  <?php } ?>
  <form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">

推荐阅读