Simple Login with CodeIgniter in PHP

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:

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['libraries'] = array('database','session');

 

$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.


$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)

This is the private page (only authenticated users can access it).


<?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.

Cheers!

Posted in Blog, PHP
49 comments on “Simple Login with CodeIgniter in PHP
  1. govarthanan says:

    it’s good one…

  2. Joe P. says:

    Nice and concise. Thanks

  3. alex mbiru says:

    this script help me a lot, keep the good work.

  4. flashbag says:

    I was just searching for simple login example. And I’ve founded it!
    Thank you!

  5. Eb says:

    thanks for the great tutorial. I’m just getting started with code igniter. Just an observation, User Model (application/models/user/php) is supposed to be User Model (application/models/user.php). Wrong?

  6. Andres Arias says:

    Fixed! Thanks for the heads up! :)

  7. “Simple Login with CodeIgniter in PHP – Code Factory” was in fact a great posting.

    In case it possessed much more pics this would be even
    much better. Regards ,Gilda

  8. Preetham says:

    thanks a lot for posting this….

  9. Tony says:

    Thanks for this! It helped me a great deal.
    It was posted back in 2011 from the looks of it, but still works line for line with the current version in 2013.

  10. Shahzeb Babar says:

    It is open for SQL injection. tried it myself.

  11. kap says:

    This is fantastic work…..

    and also thanks……

  12. SHWETA says:

    i have tried with your code and created database and tables but not getting how to run this,please help me

  13. Taukil Ali says:

    Great post .I like it.

  14. Andres Arias says:

    Hey! Can you post the error you are getting? Or send me an email (aarias_at_codefactorycr.com)

  15. julian says:

    you already put the url helper in the autoload.php so why did you still load it in the login controller?

  16. Andres Arias says:

    Good catch! It is not required in the controller as you say. I’ll fix the post.

    Thanks!

  17. Austin says:

    I’m getting a 404 on verifylogin, yet I followed your guide to the teeth. Could it be an htaccess problem?

  18. Andres Arias says:

    Good catch! I updated the code in user.php to use a more proper version of $this->db->where(), instead of concatenating strings. More info here: http://ellislab.com/codeigniter/user-guide/database/active_record.html

  19. Andres Arias says:

    Hey Austin! Well, it could be an .htaccess problem, since by using form_open(‘verifylogin’); in the

    tag, you’re using CodeIgniter’s helper to create an absolute path for the form action, instead of building the url yourself. Have you tried this without the .htaccess to see how it goes?
  20. andres says:

    hi, sorry for my english.
    how do I validate that a user is logged in, if I have multiple controllers.
    because when I click it back in my browser, and I logged out, I can see my application. I’m trying to apply your example to my application but I could not get it right. Thank you.

  21. Andres Arias says:

    In verifylogin.php (line 49) you add the user info to a key called “logged_in” in the session, so in the private pages you need to check that this “logged_in” key exists in the session, like this:

    if(!$this->session->userdata(‘logged_in’)){
    //Not logged in, redirect to a public page
    redirect(‘home’, ‘refresh’);
    }

    And to log out you can do this: $this->session->unset_userdata(‘logged_in’);

    Cheers

  22. andres says:

    if it is exactly what I’m doing pass your example to my application, but I have more drivers also I have to validate these and did what you commented:
    if (!$this->session->userdata(‘logged_in’)) {
    redirect(‘home’, ‘refresh’);
    }

    I log off, I get redirected to the login form, but when clicking back on my browser allows me to see all my application. : (

    Curiously works fine in Internet Explorer but not in Firefox, Chrome and Opera.
    Do you speak Spanish?.
    Greetings from Cali, Colombia.

  23. zul says:

    Why i get this Error :

    An Error Was Encountered

    In order to use the Session class you are required to set an encryption key in your config file.

    I already follow your instruction. anybody can help me?

  24. Jeff says:

    Hi! I get this after following your tutorial:

    “An Error Was Encountered

    Unable to load the requested class: database, session”

    Can anyone help me? I was wondering what happened?

  25. Thanks man now I am starting with codeiniter it’s very useful for me..

  26. Prashanth.Maddur says:

    its good for beginners……….

  27. Morris says:

    Thanks!!! this really help me a lot :)

  28. Christiaan Janssen says:

    Awesome tutorial. Works like a charm!

  29. peter says:

    Thank you very much, very useful. I’ve got only one problem. I think it uses only 1 session for multiple users !?
    If i log in as for example bob and in a new tab mike, then when i have a shopping cart in the “member area” and want to shop, then i add something and go to the other tab where mike is logged in and put something into the shopping cart, the tab where mike is logged in changes to bob.

    thanks in advance

  30. Andres Arias says:

    Hi Peter

    I think the problem you’re having is in your browser. The same happens to me in Firefox and Chrome, since the session is shared among tabs (e.g. you’re in amazon and open multiple tabs and add them to your cart, keeping the logged in session). You can try this with a different browser (two different browsers in the same machine) or maybe with Chrome in incognito mode, since it’s a separate window and process from the non-incognito window.

    Cheers

  31. Sebastian says:

    After doing exactly as requested in the whole login tutorial, what url should I run in my localhost given my local root is localhost/simple_login?
    pliz help…

  32. Vladimir says:

    I don’t understand one row.
    This is in function check_database($password)

    $username = $this->input->post(‘username’);

    Why you don’t put too variable $password?
    fe. $password = $this->input->post(‘username’);

    Thanks.

  33. Vladimir says:

    I made mistake. Sorry.

    I don’t understand one row.
    This is in function check_database($password)

    $username = $this->input->post(‘username’);

    Why you don’t put too variable $password?
    fe. $password = $this->input->post(‘password’);

    Thanks.

  34. jithu.majinu says:

    realy it is good tutorial for beginners

    thank you :)

  35. pantas says:

    help me an error…

    i try it on appserv 2.5.9, but i get this error..

    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, psinaga24@gmail.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.
    Apache/2.2.4 (Win32) PHP/5.2.3 Server at localhost Port 80

    please help me..

  36. angel says:

    thanks!

  37. Andres Arias says:

    Hi pantas

    Is there a way you could check Apache’s logfiles? It seems something went really wrong and threw out that 500 error. You can check for the error_log or php_error_log (depending on the lamp server you’re using).

    Cheers

  38. Andres Arias says:

    Hi Sebastian

    The url should be something like http://localhost/simple_login/index.php/login (or remove index.php if you have changed the config for this)

    Cheers

  39. Andres Arias says:

    Hi Vladimir

    As far as I understand, the form_validation methods accept only one field :( since they’re validating a field in a form. The $this->input->post(‘username’) is a trick to have both params when checking the database.

    Cheers

  40. Gopika says:

    Hi Andres

    Thank you for the tutorial. As a beginner with codeigniter, it was very helpful.

    I wanted to create this in both chinese and english.

    https://github.com/EllisLab/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n

    I had followed this steps and was able to create the language change. But then the login is not working, it is showing Call to a member function select() on a non-object.

    Any help will be appreciated.

    Thanks a lot.

  41. Barış says:

    That was really useful. I am learning the codeigniter framework and i can say it is the best sample i’ve ever seen. Thank you.

  42. funti says:

    once i have comment this line
    redirect(‘home’, ‘refresh’);
    than it works without any error message.
    but after login it will lead to index.php/verifylogin
    is it fine ?
    and what to do to redirect it to another page !

  43. aruna says:

    Really good one …. searching for simple sample application to learn codeigniter and found it here

  44. Scavanza Laziendo says:

    what is the action in the tag form in the login_view?? i don’t get it,,because if you hit the submit button nothing will happen,,oh and by the way thanks for the tutorial i love it

  45. Jack says:

    Hi,

    Your tutorial was very helpful! However when I attempt to log in I get this error:

    The requested URL /LoginTut/login/VerifyLogin was not found on this server.

    Do you know what might be the problem?

    I posted a question of my problem on StackOverflow. It describes in detail what I did and the problem I am now having.

    http://stackoverflow.com/questions/14940118/simple-login-system-using-codeigniter-returning-404-on-login#comment20967412_14940118

    I’d appreciate any help on the topic but once again fantastic tutorial!

  46. Nitish says:

    Thanks for the tutorial. I am getting the error

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Verifylogin::$form_validation

    Filename: controllers/verifylogin.php

    Line Number: 18

    line number 18 is
    $this->form_validation->set_rules(‘username’,'Username’,'trim|required|xss_clean’);

  47. Andres Arias says:

    Hi Nitish

    Do you have the line $this->load->library(‘form_validation’); before line 18? You need this line to load the validation library.

    Cheers

  48. Andres Arias says:

    Hi Scavanza

    The action in the form is added here => < ?php echo form_open('verifylogin'); ?> (login_view.php, line 9). This is the same as creating the full tag

    Thanks

1 Pings/Trackbacks for "Simple Login with CodeIgniter in PHP"

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>