At some point you might need to create a user login for your project while using the Ccodeigniter framework. For those of you who are just getting started with this, you will see within this next post that it is very simple to create.
Let’s cut right to the chase:
Create login controller
The first thing that needs to be done is the login controller for your project. Within this login, we will create an index function that will load our login view. Remember, for good programming habits, we will also include our construct, and call the parent construct as well.
Filename: login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('login_view');
}
}
?>
Once our logion controller is created, we can go ahead and create our login_view file. I will create a very simple form, without any style. That way, if needed, you can add the style that you like.
Filename: login_view.php
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<title>Jotorres Login Screen | Welcome </title>
</head>
<body>
<div id='login_form'>
<form action='<?php echo base_url();?>login/process' method='post' name='process'>
<h2>User Login</h2>
<br />
<label for='username'>Username</label>
<input type='text' name='username' id='username' size='25' /><br />
<label for='password'>Password</label>
<input type='password' name='password' id='password' size='25' /><br />
<input type='Submit' value='Login' />
</form>
</div>
</body>
</html>
If you notice above, the form action is set to – base_url()login/process. This is assuming that your base_url is set as the following: “http://yourdomain.com/”. Notice the final slash. So now we need to create a method in our controller called process. Within this method, we will call our model, and process our logic in the model. Let’s do so:
<?php
public function process(){
$this->load->model('login_model');
$result = $this->login_model->validate();
if(! $result){
$this->index();
}else{
redirect('home');
}
}
?>
Now that we have that method, we can create our login_model file. This file will have a method called validate. In this method we will query our database, looking for a user, and will return true or false, depending on the outcome. Also, we will use the codeigniter sessions class, to create a user-specific session. Let’s take a look at how its done.
Filename: login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if($query->num_rows == 1)
{
$row = $query->row();
$data = array(
'userid' => $row->userid,
'fname' => $row->fname,
'lname' => $row->lname,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
return false;
}
}
?>
We are almost finished with this login script. If we have that the validation was unsuccessful, then we need to notify the user that something is wrong. Let’s add in a message indicating something went wrong. We will add a parameter to our index function in login controller. The default message will be null, meaning there will be nothing to display, but if an error occurs, we call the method with a message. Let’s see how we go about this matter:
Filename: login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
function __construct(){
parent::__construct();
}
public function index($msg = NULL){
$data['msg'] = $msg;
$this->load->view('login_view', $data);
}
public function process(){
$this->load->model('login_model');
$result = $this->login_model->validate();
if(! $result){
$msg = '<font color=red>Invalid username and/or password.</font><br />';
$this->index($msg);
}else{
redirect('home');
}
}
}
?>
Now let’s display that message in our login_view:
Filename: login_view.php
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<title>Jotorres Login Screen | Welcome </title>
</head>
<body>
<div id='login_form'>
<form action='<?php echo base_url();?>login/process' method='post' name='process'>
<h2>User Login</h2>
<br />
<?php if(! is_null($msg)) echo $msg;?>
<label for='username'>Username</label>
<input type='text' name='username' id='username' size='25' /><br />
<label for='password'>Password</label>
<input type='password' name='password' id='password' size='25' /><br />
<input type='Submit' value='Login' />
</form>
</div>
</body>
</html>
Lastly, we need to create the members only page and controller. This controller will verify if the user is logged in, and if not, then redirect to the login page. We will create the validation within the construct, since each time the user access this ‘home’ page, this construct will run. If we were to only write it in the index function, then only the index would get validated, and not all other functions.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller{
function __construct(){
parent::__construct();
$this->check_isvalidated();
}
public function index(){
echo 'Congratulations, you are logged in.';
}
private function check_isvalidated(){
if(! $this->session->userdata('validated')){
redirect('login');
}
}
}
?>
Add Logout
For everything that get’s logged in, there should be a way to log out. It very simple, and we will add this logic to our home controller. Also, we will add a link in the members area to logout.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller{
function __construct(){
parent::__construct();
$this->check_isvalidated();
}
public function index(){
echo 'Congratulations, you are logged in.';
echo '<br /><a href=''.base_url().'home/do_logout'>Logout Fool!</a>';
}
private function check_isvalidated(){
if(! $this->session->userdata('validated')){
redirect('login');
}
}
public function do_logout(){
$this->session->sess_destroy();
redirect('login');
}
}
?>
There you have it folks, a simple logic for logging in and out a user from a website. This can obviously be enhanced to your likings as I have made this post very broad to show how quickly this can be done.
Recommendations
Something to remember is to load your session library in the autoload file. Also, you need to set an encryption key, even if you are not planning on using it, codeigniter requires you to create one.
Load the sessions library like this:
Filename: autoload.php – Can be found at: path/to/ci/folder/application/config/autoload.php
<?php
$autoload['libraries'] = array('database', 'session');
?>
To set up the encryption key, go to the file config.php
Filename: config.php – Can be found at: path/to/ci/folder/application/config/config.php
<?php
$config['encryption_key'] = 'Type in your key';
?>
With this configured, you are ready to execute the script.