Trying to put together a simple login authentication. Been at this for quite sometime, and I can't find where I'm going wrong. Pretty new to Codeigniter and OOP PHP. I know there are authentication libraries out there, but I'm not interested in using those.
Model:
function login($username, $password){
if ($this->db->table_exists($username)){
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get($username);
if($query->num_rows >= 1)
{
return true;
$data = array(
'username' => $this->input->post('username'),
'login' => true
);
$this->session->set_userdata($data);
}
}
}
Controller
function __construct(){
parent::__construct();
$this->logincheck();
}
public function logincheck(){
if ($this->session->userdata('login')){
redirect('/members');
}
}
If I just echo from the controller: $this->session->all_userdata(); I get an empty array. So the problem seems to be that the $data array in the model isn't being stored in the session.
This code is part of your problem. You're asking the database driver if a table with the same name as the username exists, and also trying to get the username and password from the same table.
if ($this->db->table_exists($username)){
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get($username);
Change the $username
in $this->db->table_exists($username);
and $this->db->get($username);
to whatever table your users are in.
I am guessing your login function is the issue:
if ($this->db->table_exists($username)){
This just doesn't look right... If your user name was admin, there there would need to be an admin table, etc... I am posting a quick example I recently wrote that seems to get the job done:
public function doLogin(){
$this->db->select('user_pass,user_id');
$query = $this->db->get_where('users', array('user_name' => $this->input->post('login')));
if($query->num_rows<1 || $query->row('user_pass')!=md5($this->input->post('password')))
return false;
$this->session->set_userdata(array('loggedin'=>true,'user_id'=>$query->row('user_id')));
return true;
}