我正在使用Codeigniter(3)进行非常简单的登录,以及两个简单的字段,即用户名和密码。我对此很新,我遇到了一些问题。这是我的控制器,用于验证用户是否输入了正确的凭据:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->helper('url');
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
}
else
{
// session data
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('admin/dashboard', $data);
}
redirect(site_url('admin/dashboard'), 'refresh');
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->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', 'Invalid username or password');
return false;
}
}
}
?>
虽然模型user.php就是这个:
function login($username, $password)
{
$this -> db -> select('id, username, password');
$this -> db -> from('users');
$this -> db -> where('username', $username);
$this -> db -> where('password', $password);
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
在我的视图中输入Welcome <?php echo $username; ?>
我得到了未定义的变量用户名。我错了什么?
答案 0 :(得分:0)
根据您的评论,您的会话工作正常,您只需要删除重定向,不知道您为什么使用?
删除此行:
redirect(site_url('admin/dashboard'), 'refresh');