我有以下控制器,它在验证表单和显示错误方面工作正常。
用户尝试登录: http: //mydomain.com/index.php/login
但是,当用户输入错误的凭据时,它会正确加载登录视图(应该如此)并正确显示错误“无效登录”,但浏览器窗口中的 URI 显示:
http://mydomain.com/index.php/verify_login(与上述相反)。
验证失败后如何重定向到“.../index.php/login”
这是有问题的代码:
<?
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form'));
$this->load->helper('url');
$this->load->view('login_page');
}
function verify_login()
{
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->index();
}
else
{
//Go to private area
redirect('private_area', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-error">Invalid username or password</div>');
return false;
}
}
}
更新: Cyrode 的解决方案修复了该问题,但现在它在加载视图时不显示来自 check_database() 函数的“无效登录”错误消息 (set_message)。有什么想法我在这里做错了吗?
更新2: 给你:
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form'));
$this->load->helper('url');
$this->load->view('login_page');
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('login_page');
}
else
{
//Go to private area
redirect('private_area', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-error">Invalid username or password</div>');
return false;
}
}
}