[eluser]Michael Wales[/eluser]
Make your form processor your index controller and add in all of your validation there. If the validation is good - add the session information, if not, make them try again. Review the code below (not a terribly secure solution, but just for learning):
Controller: user.php
Code:
<?php
class User extends Controller {
function Users() {
parent::Controller();
}
function index() {
// Check if the user is already logged in
if ($this->session->userdata('username')) {
// They are - they need to be at their control panel
redirect('user/cpanel');
}
// The user wasn't logged in - so let's present a login form
$this->load->library('validation');
$rules['username'] = 'trim|required|callback__login_check';
$rules['password'] = 'trim|required';
$this->validation->set_rules($rules);
$fields['username'] = 'username';
$fields['password'] = 'password';
$this->validation->set_fields($fields);
if ($this->validation->run()) {
// They logged in and passed
$this->session->set_userdata(array('username'=>$this->input->post('username')));
redirect('user/cpanel');
} else {
// Bad login
$this->load->view('login');
}
}
function _login_check($username) {
// Check to see if the username/password combination are correct
// Our password are stored encrypted in the database thanks to CI's security class
// We'll use that same class for comparison
$this->load->helper('security');
$password = dohash($this->validation->password);
$query = $this->db->getwhere('users', array('username'=>$username, 'password'=>$password), 1, 0);
if ($query->num_rows() > 0) {
// That's a good username/password combo
return TRUE;
} else {
$this->validation->set_message('_login_check', 'Incorrect username/password');
return FALSE;
}
}
}
?>
View: login.php
Code:
<html>
<body>
<?= $this->validation->error_string; ?>
<?= form_open('user'); ?>
<label for="username">Username:</label><br />
<input type="text" name="username" id="username" /><br />
<label for="password"Password:</label><br />
<input type="password" name="password" id="password" /><br />
<input type="submit" value="Login" />
<?= form_close(); ?>
</body>
</html>