First, sorry for my english :D
I try to make a simple login on Codeigniter without succes. I read the official documentation and reduce the script to minimum necessary. My session is empty every time i redirect o refresh my page or if i going to another controller. If i create only one controller and make simple read and write it is going well until i refresh or redirect.
This is what I want to do: 1) first controller is main controller. Load a view with a login form. This form has a action to method validation_form and then username_check callback.
2) if the user was able to logged in, i set my userdata and redirect to restriced controller, that is my restricted area.
P.S. i use library session in autoload with the option database active. I have database library in autoload too.
MAIN CONTROLLER
class Main extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function index()
{
$this->load->view('login_view');
}
public function validation_form()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|callback_username_check');
if ($this->form_validation->run() == FALSE){
echo 'validation_error';
}else{
redirect('/restricted');
}
}
public function username_check(){
$this->load->model('login_model');
$email=$this->input->post('email');
$login=$this->login_model->validate($email);
if ($login != FALSE){
return true;
}
return false;
}
}
LOGIN MODEL
class Login_model extends CI_Model{
public function __construct(){
parent::__construct();
}
public function validate($email){
// Prep the query
$this->db->where('EmailDatore', $email);
// Run the query
$query = $this->db->get('Datore');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'email' => $row->EmailDatore,
'nome' => $row->Nome,
'cognome' => $row->Cognome,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}
}
RESTRICTED CONTROLLER class Restricted extends CI_Controller{
public function __construct(){
parent::__construct();
$this->check_isvalidated();
}
public function index(){
// If the user is validated, then this function will run
echo 'Congratulations, you are logged in.';
}
private function check_isvalidated(){
if(! $this->session->userdata('validated')){
redirect('main');
}
}
}