Home » » straightforward Login through CodeIgniter into PHP

straightforward Login through CodeIgniter into PHP

Written By Unknown on April 29, 2014 | Tuesday, April 29, 2014

CodeIgniter is an open source Web Application framework built in PHP designed to make your life as a programmer easier, while allowing you good speed for development, and also good performance when the site is up and running. Being a Java developer for almoast 10 years now, when I had to move to PHP I chose CodeIgniter for the following reasons:
  • Easy to install and configure (being a newbie in PHP this was crucial)
  • Clean and elegant MVC implementation
  • Uses Active Record pattern for database access
  • Overall small footprint and good performance
Usually when you are building a program, the login/logout functionality is a must we always have to go through, so this quick tutorial will focus on this functionality, taking advantage of the benefits of using CodeIgniter instead of doing it from scratch in PHP.
Requirements
  • CodeIgniter framework.  By the time this tutorial was done, the latest version was 2.0.2
  • Any Apache/PHP/MySQL stack.  You can install the applications independently, or install one of those packages that have all of them bundled together.
Installing CodeIgniter
To install CodeIgniter, you only need to uncompress the Zip file you download from the site into your htdocs directory and you’re good to go.  We’ll configure the database access later.
Create the database
For this tutorial, you need a MySQL database with the following table:
CREATE TABLE `users` (
 `id` tinyint(4) NOT NULL AUTO_INCREMENT,
 `username` varchar(10) NOT NULL,
 `password` varchar(100) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Remember also to add at least one user.  We’ll add one user called bob with password supersecret.
insert into users (username, password) values ('bob', MD5('supersecret'));
Configure CodeIgniter

Database Access

Update the file application/config/database.php in your CodeIgniter installation with your database info:
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'yourdbusername';
$db['default']['password'] = 'yourdbpassword';
$db['default']['database'] = 'yourdbname';
Default Controller
We need to tell CodeIgniter to land into our login page instead of the default welcome page.  Update the file application/config/routes.php in your CodeIgniter installation with you controller’s name.  We’ll call our landing controller login.
$route['default_controller'] = "login";
Default Libraries
In the file application/config/autoload.php you can configure the default libraries you want to load in all your controllers.  For our case, we’ll load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation
$autoload['helper'] = array('url');
$autoload['libraries'] = array('database','session');
Encryption Key
When you use the session library, you need to set the encryption_key in the file application/config/config.php.
$config['encryption_key'] = 'REALLY_LONG_NUMBER';
The Code
Here are the actual Views, Controllers and Model we are using for the login functionality.

User Model (application/models/user.php)

<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('id, username, password');
   $this -> db -> from('users');
   $this -> db -> where('username', $username);
   $this -> db -> where('password', MD5($password));
   $this -> db -> limit(1);

   $query = $this -> db -> get();

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }
}

?>

Login Controller (application/controllers/login.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   $this->load->helper(array('form'));
   $this->load->view('login_view');
 }

}

?>

Login View (application/views/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">
 <head>
   <title>Simple Login with CodeIgniter</title>
 </head>
 <body>
   <h1>Simple Login with CodeIgniter</h1>
   <?php echo validation_errors(); ?>
   <?php echo form_open('verifylogin'); ?>
     <label for="username">Username:</label>
     <input type="text" size="20" id="username" name="username"/>
     <br/>
     <label for="password">Password:</label>
     <input type="password" size="20" id="passowrd" name="password"/>
     <br/>
     <input type="submit" value="Login"/>
   </form>
 </body>
</html>

VerifyLogin Controller (application/controllers/verifylogin.php)

This controller does the actual validation of the fields and checks the credentials against the database.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', '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;
   }
 }
}
?>

Home Controller (application/controllers/home.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class Home extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home_view', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('home', 'refresh');
 }

}

?>

Home Page View (application/views/home_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">
 <head>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body>
   <h1>Home</h1>
   <h2>Welcome <?php echo $username; ?>!</h2>
   <a href="home/logout">Logout</a>
 </body>
</html>
The code is pretty easy to follow and understand.  Also, you can download the code from here, so you can install it and test it in your location.  You’ll only need a full installation of CodeIgniter 2.0.2 and the table in your MySQL database.  If you need any help, feel free to leave us a comment or shoot us an email. Also, this code uses a pretty basic form validation from CodeIgniter.  If you need a more complex validation process, check CodeIgniter’s Form Validation docs at their site.

0 comments:

Post a Comment