我有一个使用CI表单验证的登录表单。
表单位于domain.com/login
它运行一个名为validate_credentials的函数,如果验证失败,则重新加载视图。问题是URL继续显示:
domain.com/login/validate_credentials
如何删除/ validate_credentials?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div><br />');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login/login');
}
else
{
$this->load->view('clock/clock');
}
}
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) {// staff credentials validated...
$data = array(
'email' => $this->input->post('email'),
'staff_logged_in' => TRUE
);
$this->session->set_userdata($data);
redirect('clock/clock');
}
else { // not validated reload index function
$this->index();
}
}
}
答案 0 :(得分:1)
不是调用其他控制器函数,而是重定向到索引。因为CodeIgniter中的控制器中的函数正在设置URL方案,所以现在的方法就是执行索引函数,但是在validate_credentials函数(和URL)中。
这样做:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div><br />');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login/login');
}
else
{
$this->load->view('clock/clock');
}
}
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) {// staff credentials validated...
$data = array(
'email' => $this->input->post('email'),
'staff_logged_in' => TRUE
);
$this->session->set_userdata($data);
redirect('clock/clock');
}
else { // not validated reload index function
//$this->index();
$this->load->helper('url'); //to enable redirect function
redirect('index'); //based on your index url
}
}
}
如果您需要显示错误或成功消息,请参阅CodeIgniter的session library的flash_message,但这是一个示例。
在重定向到索引之前,在控制器中设置错误消息juste:
$this->load->library('session');
$this->session->set_flashdata('error_message', "This is my error message");
在索引视图中,如果存在则显示它:
<?if($this->session->flashdata('error_message')):?>
<div class="nNote nFailure"><p><?=$this->session->flashdata('error_message');?></p></div>
<?endif;?>
请注意,flash_message会显示一次。这意味着您的索引将显示您的错误,然后销毁会话消息。这是flash_message的目的,正确而简单地显示错误消息。