Sunday, July 1, 2012

Login Logout CodeIgniter

http://www.codefactorycr.com/login-with-codeigniter-php.html


Simple Login with CodeIgniter in PHP

Apr 18, 2011   //   by aarias   //   Blog, PHP  //  No Comments
Code Igniter logoCodeIgniter 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 almost 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:
1CREATE TABLE `users` (
2 `id` tinyint(4) NOT NULL AUTO_INCREMENT,
3 `username` varchar(10) NOT NULL,
4 `password` varchar(100) NOT NULL,
5 PRIMARY KEY (`id`)
6) 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.
1insert 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:
44$db['default']['hostname'] = 'localhost';
45$db['default']['username'] = 'yourdbusername';
46$db['default']['password'] = 'yourdbpassword';
47$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.
41$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
55$autoload['libraries'] = array('database','session');
67$autoload['helper'] = array('url');

Encryption Key

When you use the session library, you need to set the encryption_key in the file application/config/config.php.
227$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)

1<?php
2Class User extends CI_Model
3{
4 function login($username, $password)
5 {
6   $this -> db -> select('id, username, password');
7   $this -> db -> from('users');
8   $this -> db -> where('username = ' . "'" . $username . "'");
9   $this -> db -> where('password = ' . "'" . MD5($password) . "'");
10   $this -> db -> limit(1);
11 
12   $query = $this -> db -> get();
13 
14   if($query -> num_rows() == 1)
15   {
16     return $query->result();
17   }
18   else
19   {
20     return false;
21   }
22 }
23}
24?>

Login Controller (application/controllers/login.php)

1<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2 
3class Login extends CI_Controller {
4 
5 function __construct()
6 {
7   parent::__construct();
8 }
9 
10 function index()
11 {
12   $this->load->helper(array('form', 'url'));
13   $this->load->view('login_view');
14 }
15 
16}
17 
18?>

Login View (application/views/login_view.php)

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <head>
4   <title>Simple Login with CodeIgniter</title>
5 </head>
6 <body>
7   <h1>Simple Login with CodeIgniter</h1>
8   <?php echo validation_errors(); ?>
9   <?php echo form_open('verifylogin'); ?>
10     <label for="username">Username:</label>
11     <input type="text" size="20" id="username" name="username"/>
12     <br/>
13     <label for="password">Password:</label>
14     <input type="password" size="20" id="passowrd" name="password"/>
15     <br/>
16     <input type="submit" value="Login"/>
17   </form>
18 </body>
19</html>

VerifyLogin Controller (application/controllers/verifylogin.php)

This controller does the actual validation of the fields and checks the credentials against the database.
1<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2 
3class VerifyLogin extends CI_Controller {
4 
5 function __construct()
6 {
7   parent::__construct();
8   $this->load->model('user','',TRUE);
9 }
10 
11 function index()
12 {
13   //This method will have the credentials validation
14   $this->load->library('form_validation');
15 
16   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
17   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
18 
19   if($this->form_validation->run() == FALSE)
20   {
21     //Field validation failed.  User redirected to login page
22     $this->load->view('login_view');
23   }
24   else
25   {
26     //Go to private area
27     redirect('home', 'refresh');
28   }
29 
30 }
31 
32 function check_database($password)
33 {
34   //Field validation succeeded.  Validate against database
35   $username = $this->input->post('username');
36 
37   //query the database
38   $result = $this->user->login($username, $password);
39 
40   if($result)
41   {
42     $sess_array = array();
43     foreach($result as $row)
44     {
45       $sess_array = array(
46         'id' => $row->id,
47         'username' => $row->username
48       );
49       $this->session->set_userdata('logged_in', $sess_array);
50     }
51     return TRUE;
52   }
53   else
54   {
55     $this->form_validation->set_message('check_database', 'Invalid username or password');
56     return false;
57   }
58 }
59}
60?>

Home Controller (application/controllers/home.php)

This is the private page (only authenticated users can access it).
1<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2session_start(); //we need to call PHP's session object to access it through CI
3class Home extends CI_Controller {
4 
5 function __construct()
6 {
7   parent::__construct();
8 }
9 
10 function index()
11 {
12   if($this->session->userdata('logged_in'))
13   {
14     $session_data = $this->session->userdata('logged_in');
15     $data['username'] = $session_data['username'];
16     $this->load->view('home_view', $data);
17   }
18   else
19   {
20     //If no session, redirect to login page
21     redirect('login', 'refresh');
22   }
23 }
24 
25 function logout()
26 {
27   $this->session->unset_userdata('logged_in');
28   session_destroy();
29   redirect('home', 'refresh');
30 }
31 
32}
33 
34?>

Home Page View (application/views/home_view.php)

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <head>
4   <title>Simple Login with CodeIgniter - Private Area</title>
5 </head>
6 <body>
7   <h1>Home</h1>
8   <h2>Welcome <?php echo $username; ?>!</h2>
9   <a href="home/logout">Logout</a>
10 </body>
11</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.

No comments:

Post a Comment