Simple Login using CodeIgniter & Database

Ok now I will explain about to create simple login using CodeIgniter (Update using codeigniter version 3.0) & Database (Example I use MySQL). And in this case, I think you’ve installed CodeIgniter on your local PC or localhost. Next, just follow this intructions:

  1. Create Database.
    CREATE TABLE `users` (
      `id_user` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) NOT NULL,
      `password` varchar(50) NOT NULL,
      PRIMARY KEY (`id_user`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    Note:
    Oh ya remember to add one row or data to table admin, example with name “Imron” and password “password” with md5.

    INSERT INTO users(username, password) VALUES('Imron',md5('password'));
    

    And for certainty, use the select query to see the data that we have just entered.

    SELECT * FROM users;
     id_user | username |             password             
    ---------+----------+----------------------------------
           1 | Imron    | 5f4dcc3b5aa765d61d8327deb882cf99
    (1 row)
    
  2. Configure database on CodeIgniter.
    Update the file yourcodeigniter/application/config/database.php in your CodeIgniter installation with your database info:

    $active_group = 'default';
    $query_builder = TRUE;
    
    $db['default'] = array(
    	'dsn'	=> '',
    	'hostname' => 'localhost',
    	'username' => 'yourusername',
    	'password' => 'yourpassword',
    	'database' => 'yourdatabase',
    	'dbdriver' => 'mysqli',
    	'dbprefix' => '',
    	'pconnect' => FALSE,
    	'db_debug' => TRUE,
    	'cache_on' => FALSE,
    	'cachedir' => '',
    	'char_set' => 'utf8',
    	'dbcollat' => 'utf8_general_ci',
    	'swap_pre' => '',
    	'encrypt' => FALSE,
    	'compress' => FALSE,
    	'stricton' => FALSE,
    	'failover' => array(),
    	'save_queries' => TRUE
    );
    
  3. Set Encryption Key config CodeIgniter
    We need set Encryption Key to enable session libraries. Open yourcodeigniter/application/config/config.php

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | If you use the Encryption class, you must set an encryption key.
    | See the user guide for more info.
    |
    | http://codeigniter.com/user_guide/libraries/encryption.html
    |
    */
    $config['encryption_key'] = 'learn_ci';
    
  4. Then now open yourcodeigniter/application/config/autoload.php and change the code like this:
    $autoload['libraries'] = array('session');
    
    
    /*
    | -------------------------------------------------------------------
    |  Auto-load Drivers
    | -------------------------------------------------------------------
    | These classes are located in the system/libraries folder or in your
    | application/libraries folder within their own subdirectory. They
    | offer multiple interchangeable driver options.
    |
    | Prototype:
    |
    |	$autoload['drivers'] = array('cache');
    */
    
    $autoload['drivers'] = array();
    
    
    /*
    | -------------------------------------------------------------------
    |  Auto-load Helper Files
    | -------------------------------------------------------------------
    | Prototype:
    |
    |	$autoload['helper'] = array('url', 'file');
    */
    
    $autoload['helper'] = array('url');
    

    Explanations:
    This function is used to automatically load helper and library (like url and session) if we run codeigniter. So if we load helper and library in this file, we don’t need to load helper or library manually in all controller like this code:

    $this->load->helper('url')
    or
    $this->load->library('session')
    

    So if we write in this autoload.php, we write enough just once for all controllers.

  5. Code
    Create yourcodeigniter/application/models/Login_model.php:

    Explanations:

    • Line 13 is using to load database, so with this function we can connect to database with the config is from database.php (above file)
    • Line 17-19 is Query builder from ci, if we translate the code, may be like this:
      SELECT * FROM users WHERE username = "$data['username']" AND password = "$data['password']"
      

      For more info you can read from this http://www.codeigniter.com/user_guide

    • Line 23 is the destructor. This is PHP OOP feature, for more info read this http://php.net/manual/en/language.oop5.decon.php

    Then create yourcodeigniter/application/controllers/Login.php:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    /**
     * @name Login.php
     * @author Imron rosdiana
     */
    class Login extends CI_Controller
    {
    
        function __construct() {
            parent::__construct();
            $this->load->model("login_model", "login");
            if(!empty($_SESSION['id_user']))
                redirect('home');
        }
    
        public function index() {
            if($_POST) {
                $result = $this->login->validate_user($_POST);
                if(!empty($result)) {
                    $data = [
                        'id_user' => $result->id_user,
                        'username' => $result->username
                    ];
    
                    $this->session->set_userdata($data);
                    redirect('home');
                } else {
                    $this->session->set_flashdata('flash_data', 'Username or password is wrong!');
                    redirect('login');
                }
            }
    
            $this->load->view("login");
        }
    }
    

    Explanations:

    • Line 13, this function is used to load model. In this project we create Login_model.php, so this function is to load it and we using alias. So with the alias we can call the model with this $this->login->namefunction, and if we not using alias we can call the model with $this->login_model->namefunction
    • Line 14-15 is using to validate session, so if we have logged in before, then we don’t need login again and the page is redirect to Home controller
    • Line 19 is using if we get the post from login page
    • Line 20 is to load model, and get the save the result to $result variable
    • Line 21-28 is used to check if $result not empty or the user already exist on database, we create the session and go to home page
    • Line 29-32 is used if user not in database, so login is failed and back again to login page
    • Line 35 is to load form login

    Then create yourcodeigniter/application/controllers/Home.php

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    /**
     * @name Home.php
     * @author Imron Rosdiana
     */
    class Home extends CI_Controller
    {
    
        function __construct() {
            parent::__construct();
    
            if(empty($this->session->userdata('id_user'))) {
                $this->session->set_flashdata('flash_data', 'You don\'t have access!');
                redirect('login');
            }
        }
    
        public function index() {
            $this->load->view('home');
        }
    
        public function logout() {
            $data = ['id_user', 'username'];
            $this->session->unset_userdata($data);
    
            redirect('login');
        }
    }
    

    Explanations:

    • Line 14-17 is used if the user accesses the home page before login, so the user will be redirect to login page
    • Line 20-22 is to load home page if user already login
    • Line 24-28 is used if user logout from home page, so we must remove the session

    The last is create home page on yourcodeigniter/application/views/home.php:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Learn CI</title>
        </head>
        <body>
            <h1>Welcome <?= $this->session->userdata('username') ?></h1>
            <a href="<?= site_url('home/logout') ?>">Logout</a>
        </body>
    </html>
    

    And create login page on yourcodeigniter/application/view/login.php:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Learning CI</title>
    </head>
    <body>
        <?php if(isset($_SESSION)) {
            echo $this->session->flashdata('flash_data');
        } ?>
    
        <form action="<?= site_url('login') ?>" method="post">
            <label for="username">Username</label>
            <input type="text" name="username" />
            <label for="password"></label>
            <input type="text" name="password" />
            <button type="submit">Login</button>
        </form>
    </body>
    </html>
    

Very easy if you understand this. 😀
Full Code, download in here https://www.mediafire.com/?luzehcvj301dbwv

56 comments

  1. Hi I did follow your steps but when I try to load (or autoload) database library I get this error:

    Unable to connect to your database server using the provided settings.

    Filename: core/Loader.php

    Line Number: 346

    Any hint?

    1. Ok, there was an error in username. Tku anyways (note: there is a typo, your first query creates a namE_admin and later on you keep using namA_admin.)

  2. It is appropriate time to make some plans for the longer term and it’s time to be happy. I’ve read this post and if I may just I wish to counsel you few attention-grabbing things or suggestions. Perhaps you could write subsequent articles regarding this article. I wish to learn more things about it!

  3. Hi to every body, it’s my first visit of this blog; this website consists of remarkable and really fine stuff in support of readers.

  4. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My website is in the exact same niche as yours and my users would really benefit from a lot of the information you present here. Please let me know if this okay with you. Thanks!

  5. I believe everything published was actually very logical. However, what about this? what if you wrote a catchier post title? I mean, I don’t want to tell you how to run your blog, but suppose you added a title to possibly get a person’s attention? I mean Simple Login using CodeIgniter & Database is a little boring. You ought to look at Yahoo’s home page and note how they write news titles to get viewers to open the links. You might try adding a video or a related pic or two to get readers interested about everything’ve got to say. In my opinion, it would make your website a little bit more interesting.

  6. I just couldn’t go away your website before suggesting that I extremely enjoyed the standard info an individual provide on your guests? Is gonna be again ceaselessly to check out new posts

  7. What’s up, all the time i used to check webpage posts here in the early hours in the break of day, for the reason that i love to find out more and more.

    1. Now I’m busy working on the thesis, and I hope you understand. And in fact this previous blog is just my personal notes in learning coding. So when I found the problem and I was able to finish it, then I will write on this blog, and while this is my coding is delayed because I had to do some of my homework first. And thank you for the trust you to always visit this blog. Another time, I will write again and will not make you wait a long time. 😀

  8. Hello mates, how is everything, and what you want to say concerning this article, in my view its genuinely amazing in favor of me.

  9. I’ve learn some good stuff here. Definitely worth bookmarking for revisiting. I wonder how much attempt you place to create this type of magnificent informative web site.

  10. Hey there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept chatting about this. I will forward this article to him. Fairly certain he will have a good read. Thank you for sharing!

  11. hey there and thank you for your info – I have definitely picked up anything new from right here. I did however expertise several technical points using this site, since I experienced to reload the website many times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will sometimes affect your placement in google and could damage your quality score if ads and marketing with Adwords. Well I am adding this RSS to my e-mail and can look out for much more of your respective interesting content. Ensure that you update this again very soon.

  12. Hello! Someone in my Myspace group shared this site with us so I came to check it out. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Fantastic blog and superb style and design.

  13. What’s up everyone, it’s my first visit at this web page, and post is truly fruitful for me, keep up posting these types of articles or reviews.

  14. whoah this weblog is fantastic i really like reading your posts. Stay up the good work! You know, a lot of individuals are searching around for this information, you can aid them greatly.

  15. Someone essentially lend a hand to make critically posts I might state. This is the first time I frequented your web page and up to now? I amazed with the analysis you made to create this particular post extraordinary. Excellent activity!

  16. Hello, i believe that i noticed you visited my weblog thus i came to return the want?.I am attempting to in finding things to enhance my web site!I suppose its good enough to use some of your concepts!!

  17. If you are going for best contents like I do, only pay a quick visit this web site all the time because it offers quality contents, thanks

  18. Your style is very unique compared to other folks I’ve read stuff from. Thanks for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  19. I’m amazed, I must say. Rarely do I come across a blog that’s both educative and interesting, and let me tell you, you’ve hit the nail on the head. The problem is something which not enough men and women are speaking intelligently about. Now i’m very happy I came across this during my search for something relating to this.

  20. Hi there everybody, here every one is sharing these kinds of knowledge, therefore it’s nice to read this web site, and I used to go to see this blog every day.

  21. This design is wicked! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  22. I’m impressed, I have to admit. Rarely do I come across a blog that’s both equally educative and entertaining, and without a doubt, you have hit the nail on the head. The problem is something that not enough folks are speaking intelligently about. Now i’m very happy I found this during my search for something regarding this.

  23. What’s up to all, the contents existing at this website are genuinely awesome for people knowledge, well, keep up the nice work fellows.

  24. I’ve been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I ultimately stumbled upon this website. Studying this information So i am happy to convey that I’ve a very excellent uncanny feeling I came upon just what I needed. I such a lot unquestionably will make certain to do not omit this site and provides it a look on a continuing basis.

  25. Greetings! Very helpful advice within this article! It is the little changes which will make the most important changes. Thanks a lot for sharing!

  26. Hi it’s me, I am also visiting this web site on a regular basis, this web page is in fact good and the users are really sharing good thoughts.

  27. Very good blog! Do you have any tips for aspiring writers?

    I’m planning to start my own blog soon but I’m a little lost
    on everything. Would you propose starting with a free platform like WordPress or go
    for a paid option? There are so many choices out there that I’m totally overwhelmed ..

    Any suggestions? Appreciate it!

  28. I am now not positive the place you are getting your information, but great topic. I must spend some time learning more or understanding more. Thanks for magnificent information I was looking for this information for my mission.

  29. it’s work. But when I’m filling wrong username & password, I don’t get a warning.
    how to resolve it? hehehe

    1. This work perfectly bro. You can see this code if username or password is wrong.
      <?php if(isset($_SESSION)) {
      echo $this->session->flashdata(‘flash_data’);
      } ?>

Leave a reply to imron02 Cancel reply