CodeIgniter From Scratch: Day 6
videos

CodeIgniter From Scratch: Day 6 – Login

This entry is part 6 of 17 in the CodeIgniter From Scratch Session
« PreviousNext »

In today’s hour long video tutorial, we’ll be doing a lot! We’ll implement a login and signup form that will allow us to lock down certain sections of our fictional site. As you’ll find, working with sessions in CodeIgniter is a cinch!

Catch Up

Day 6: Sessions

More Viewing Options

Login Form
Signup Form

P.S. The Logout Button

I forgot to add the “logout” button during the screencast. There was so much to cover, that I was bound to forget something! Luckily, it’s really easy. Simply add a link, to the “members” area, which links to the login class, and a “logout” method (login/logout). Then, all we must do is destroy the user’s session, and redirect them back to the login form. Download the source code if confused.

function logout()
{
	$this->session->sess_destroy();
	$this->index();
}

Hope you Enjoy it!

Keep in mind that we’re just scratching the surface, in terms of flexibility and security. We can – and very well may – take things much further. But this should get you started!

Thank you, Screencast.com!


Screencast.com

…for providing the hosting for these video tutorials.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • leo

    I am getting the “You are NOT authorized’ message again and again. Any help?

    This is what is in my Login class:

    function validate_credentials()
    {
    $this->load->model(‘membership_model’);
    $query = $this->membership_model->validate();

    if($query) // if the user’s credentials are validated
    {
    $data = array(
    ‘username’ => $this->input->post(‘username’),
    ‘is_logged_in’ => true
    );

    $this->session->set_userdata($data);
    redirect(‘chat/index’);
    }
    else
    {
    $this->index();
    }
    }

    This is the similar to the “Site” class in the TUT.

    class Chat extends CI_Controller {

    public function __construct()
    {
    parent::__construct();
    $this->is_logged_in();
    }

    public function index()
    {
    $data['main_content'] = ‘chat_view’;
    $data['user_id'] = $this->session->userdata(‘username’);
    $this->load->view(‘includes/template’, $data);
    }

    function is_logged_in()
    {
    $is_logged_in = $this->session->userdata(‘is_logged_in’);
    if(!isset($is_logged_in) || $is_logged_in != true)
    {
    echo ‘You don\’t have permission to access this page. Login‘;
    die();
    $this->load->view(‘login_form’);
    }
    }
    }

    • http://www.radumicu.info radum

      If you are testing on localhost, go to config and see if this settings work for you

      $config['sess_cookie_name'] = ‘cisession’;
      $config['sess_expiration'] = 7200;
      $config['sess_expire_on_close'] = TRUE;
      $config['sess_encrypt_cookie'] = TRUE;
      $config['sess_use_database'] = TRUE;
      $config['sess_table_name'] = ‘ci_sessions’;
      $config['sess_match_ip'] = TRUE;
      $config['sess_match_useragent'] = TRUE;
      $config['sess_time_to_update'] = 300;

      $config['cookie_prefix'] = ”;
      $config['cookie_domain'] = ”;
      $config['cookie_path'] = ‘/’;
      $config['cookie_secure'] = FALSE;

      Be sure to clear cache and empty the ci_session table from the db.

  • http://marlonansale.wordpress.com marlon ansale

    I got error when using mysql_num_rows is it deprecated? I could not logged in the account i use this code to my class mebership_model

    function validate(){
    $condition = FALSE;
    $this->db->where(‘username’, $this->input->post(‘username’));
    $this->db->where(‘password’, md5($this->input->post(‘password’)));
    $query = $this->db->get(‘login’);

    if($query->num_rows == 1){
    $condition = TRUE;
    }

    return $condition;
    }

    please hel[ >:(..,

  • CIBeginner

    Hi! thank you very much for your tutorials! It is really helping me a lot, we have a CI project (given today) due after two days, and because i have no background in php and CI, I was sure that I won’t be able to do it. But, your videos gave me hope! I understand CI better now, thank you again!
    I just have a few questions: (I hope you don’t mind!)

    1) how would I check if the user is an admin? In my database, I have a field named Is_admin which has the value 1 if the user is an admin, a link in the home page will be enabled/disabledd, if not it is not visible/enabled…

    2) How can I display an message prompt whenever the user enters invalid/empty information?

    again thank you very much for your superb tutorials and your help :)

  • zahid

    Dear jeff..

    according to your tutorial day 6 login , in my controller , it is not redirecting me to site/members_area it only redirect to the validate_credentials ….

    please i need help as i am stuck over this..

    • Marcus

      I had the exact same problem as you, I even checked most of the replies in this thread… after an hour or so i replaced:

      redirect(‘site/members_area’);

      With:

      redirect(“site/members_area”);

      Now it works like a charm! i hope this helps! I have seen a number of people on here with the same issue as me. I wonder why ‘ ‘ wont work but ” ” does?

      • http://www.phpforfun.com/ Matt

        Hi Marcus,

        The fix you suggested wasn’t working for myself. It is very annoying and if I figure it out I will definitely reply. But if anyone has any other suggestions, I’m sure most of us are open to hearing.

        Thanks For the Videos NetTuts!

  • Robo

    Thanks for sharing these great tutorials Jeffrey.

  • Sven

    My styles (styles.css) do not get applied when I click the Create Account button.

    They work fine on the Login form, but not on the Sign Up form.

    Now, what thing could cause that to happen? I followed the tutorial step by step, so I really don’t get HOW this screws up!? The styles are added in the header, and it’s the exact same header I’m using all the time. This has to be a bug!?

    Anyone have any ideas?

    • http://ever-flow.net veritascs

      Try referencing your styles via the whole URL and not just relative.

      I’m guessing you’re doing something like ‘assets/css/styles.css’, try ‘http://domain/assets/css/styles.css’

      I had this issue recently.

  • Attila

    Hi, i just couldnt find this in the documentation: $this->db->where(). Can somebody explain this to me pls?

  • Derek

    Why didn’t you go over a logout function? I know it was a big tutorial to begin with but that’s the other half of the puzzle.

  • http://develop21.com Chris

    Great tutorial, just what I was looking for. Thank you!

  • CJ

    i noticed you did $query = $this->something in the IF statement… won’t that IF always be true becuase it’s just returning a value? wouldn’t it make more sense to just do if($this->something). i don’t know if i’m wrong or you just missed it.

    • CJ

      sorry. this is in regards to the member creation process. the query I’m referring to is when you call the model to create it.

    • Sanjay Maurya

      Hi CJ,

      Did you get your answer till now?

      With statement “$query = $this->something” in IF statement, we are comparing and assigning both. We are assigning result of “$this->something” in $query and testing status of $query at the same time. This is little bit shorter code.

  • mash

    THANKS!!!!!! Very Helpful

  • http://johnmeher.com John Meher

    I know this tutorial has been around for awhile but you can also do;

    $this->session->sess_destroy();
    redirect(‘some/page’);

    Thanks for the tutorial, would like to see more!

  • Andrew Kimball

    These tutorials have really helped me gain a better understanding of MVC! Thanks!

    For those having the problem with the login validation, change :

    $query->num_rows == 1

    to

    $query->num_rows() == 1

    • Andrew Kimball

      Actually what I posted above doesn’t make a difference. It turns out that I had multiple records in the database with the same username and password. Since we are checking for $query->num_rows() == 1, the conditional statement was never executed.

  • helena

    i can’t get the css files right. could you explain how the css files are called?

    “Unable to load the requested file: stylesheet.css”
    exactly on loading the basepath

    i am using the latest version, so there are some differences to your version here.
    This was an excellent tutorial, btw.

  • helena

    hi again!
    Forget about my previous problem, i had to modify sth, thanks the best tutorial! :)

  • Marcelo

    Hi everyone, I’ve just complete the tutorial but here I have some weird thing happening. When I try to access the members area without the $is_logged_in set, the system redirects to the login screen, just like I expected, but it also outputs the member page contents after the login page content… Does anyone have any idea to solve this? I´m using the last version available on this date.

    Here is the SITE controller:

    is_logged_in();
    }

    public function restrito()
    {
    $this->load->view(‘site/site_main’);
    }

    public function is_logged_in(){
    $is_logged_in = $this->session->userdata(‘is_logged_in’);

    if(!isset($is_logged_in) || $is_logged_in != TRUE){
    $data['main_content'] = “inicial”;
    $this->load->view(‘includes/template’, $data);
    }
    }

    }

  • labidi

    i need to save the date of last logged in of each client , i thought about adding a column (‘last_access’, date) in clients table , any better idea ?

    • Matteo

      That is easy to do, and you don’t need CI to do it. Just add the field in PHP MyAdmin and then set it to automatically update each time the record is written.

  • Matteo

    You should add a screen shot or CREATE script of your MySQL database so that we could reproduce it for testing/dev purposes without having to guess on its structure.

    Great tut!

  • henry

    The md5 function is not working for me in the site model. Every time i include it as

    $this->db->where(‘password’, md5($this->input->post(‘password’)));

    my form just loads the else clause in the validate_credentials function. When i take it out and insert a ‘naked’ password in to my database to test, i get the proper redirection to the members area. This has got me stuck for hours on end. What could be the problem why is the md5 function causing problems.

  • Flex

    function is_logged_in(){

    $is_logged_in = $this->session->userdata(‘is_logged_in’);
    if(!isset($is_logged_in) || $is_logged_in != true){
    redirect(‘login’);
    }
    }

    doesnt work with load view, I use redirect.

    • http://rartdesign.it RArtDesign

      The logic is that you load views and models into your controllers.

      If you followed the tutotial, both “site.php” and “login.php” in your case are controllers, in the “controllers” folder.

      So I presume what you did is tryied to load the controller “login” into the controller “site” refferencing “login” as a view:

      $this->load->view(‘login’);

      wich doesn’t exist.

      Best regards ;) !

  • http://www.lollypop.gr GeorgeD

    Amazing tutorial. Its very hard to follow, especially because I am a newbie in the OOP stuff. But really, you have made a great job with this tutorial.

    I understood why Frameworks and OOP is the way to go with scripting.

    Many many thanks mate.

  • http://rartdesign.it Sebastian

    Amazing FIVESTAR+ tutorial Jeffrey !
    I’m new to CodeIgniter and this video was one of the first I’ve seen on making my very first basic aknowledgments on this great framework. Thank you, It helped me a lot to get the mechanism !

    I’ll also report an issue:
    You forgot to make a check wether the inputed ‘username’ is already in the database before inserting new data…

    For as far as I’ve arrived, I believe that’s simply done by adding the ‘is_unique[table.field]‘ rule to the ‘set_rules’ method from the ‘form_validation’ class called on the ‘username’ input field !?

    $this->form_validation->set_rules(‘username’, ‘Usernmae’, ‘trim|required|min_length[4]|is_unique[membership.username]‘);

    Best regards!

  • http://rartdesign.it RArtDesign

    I presume my last post was cancelled by “moderation” due to the fact that the spotted issue has already been “spoted” and solved by other users in the previous posts… my bad, didn’t checked.

    But I still wan’t to thanks a lot fot the videotutorial that has been so illuminating concerning CodeIgniter, since that part of the post got lost too…

    FIVESTAR Videotutorial Jeffrey! Many thanks! You rock!

  • Ciprian

    Great tutorial! Thank you very much. I would love to see how to include Facebook and Twitter login to this. I haven’t seen any tutorials on that.

  • http://midknightdesigns.com David

    In case some of you are using Bitnami local to work on this, there is a bit of a trick to get the css working…

    Move the CSS folder to frameworks/codeigniter/htdocs

    Now the code for base_url should work.

    <link rel="stylesheet" href="css/style.css”>

    Another friendly helper, the construct in this video is different from the 2.x version most people are running.

    class Site extends CI_Controller {

    function __construct() {
    parent::__construct();
    $this->is_logged_in();
    }

    Hope that helps some of you who were as stuck as I was :-P

    • Rez

      Sure did, thanks!

    • nycpicasso

      Wow, thanks! I have been stuck on this for hours since the video is from 2009 and things have changed since.

  • Jmorris

    The links for this tutorial seem to be bad or missing. Can anyone point me in the right direction?

  • Rahul Patil

    Another great tutorial.. Loving your series. Now, I am understanding Codeigniter and PHP in better sense..

    Thanks a ton Jeffrey :)

  • Ryan

    The video link is broken. Please fix it.
    Thank you.

  • David

    Hi guys, I get a blank view with no HTML Mark Up after logging out. I am using CodeIgniter 2.1.1. I don’t have any error messages Kindly assist.

    [CODE]

    is_logged_in();
    }

    function members_area() {
    $this->load->view(‘members_area’);
    }

    function is_logged_in() {

    $is_logged_in = $this->session->userdata(‘is_logged_in’);

    if (!isset($is_logged_in) || $is_logged_in != TRUE) {

    die();

    $this->load->view(‘login_form’); //Redirects back to login form
    }
    }

    }

    [CODE]

  • Siddharth Sakhadeo

    I cannot get any output on styles though I’ve linked the stylesheet every possible way. What could be the problem.

    • http://www.darknessfalls.org.uk Ged

      view source and click on the link for the style sheet. 99.9% guaranteed you’ll get a 404 error – so you’ll need to check your paths to your style folder.

  • http://devrabbit.com Michael Calkins

    This was an especially good tutorial! Thank you so much Jeff!

  • spider

    Hello i need help ASAP everytime i click on login it directs me to login/validatecredentials instead of the members_area section

  • Daniel

    Hi Jeffrey, thanx for your great tutorials on codeigniter, they are jus awesome. Since the logout wasn’t included in the video tutorial, i tried the one that you gave above, however after implementin the code it didn’t work.
    When I logout from the members area and I click the browser’s back button, it redirects me back to the members area which show that the session wasn’t really destroyed. Please help me out on this small issue.

  • http://www.darknessfalls.org.uk Ged

    By God this one is a POS – if I’m lucky I can get 20 seconds before it freezes. Please guys never ever ever use blip tv again. And this is the one I really needed as well.

  • Andrew

    I followed the tutorial and when just trying to log in (with valid or invalid credentials) it hangs at the url http://localhost:8888/ci/index.php/hw/validate_credentials

    it does not actually load this line (the first line of function validate_credentials, it stops at it (tested with echos)
    $this->load->model(‘membership_model’);

    Suggestions?

    • http://www.facebook.com/sergiodk5 Asterios Patsikas

      any solutions found??

      • http://www.facebook.com/sergiodk5 Asterios Patsikas

        ok guys I just insert in the membership_model the following code and works perfectly!

        class Membership_model extends CI_Model{

        function validate(){

        $this->db->where(‘username’, $this->input->post(‘username’));

        $this->db->where(‘password’, md5($this->input->post(‘password’)));

        $query = $this->db->get(‘membership’);

        if($query->num_rows != 0){

        $validate=true; // <– this is the extra parameter that i have added!

        return $validate;

        }

        }

        }

      • http://www.facebook.com/profile.php?id=517826655 Lina Fayez

        Many thanks :)

      • hassan

        not working for me . plz help :(

      • Master Yoda

        After searching online for a while and not finding any concrete solution for this problem with CI 2.x, I spent an hour or so working on it and this worked for me:

        function validate()

        {

        $this->db->where('username', $this->input->post('username'));

        $this->db->where('password', sha1($this->input->post('password')));

        $query = $this->db->get('user'); // 'user' is my database table's name.

        return $query; // This is the extra line I added in.

        if ($query->num_rows == 1)

        {

        return true;

        }

        }

      • Rajith Wijepura

        You cant return 2 values from one function

      • hassan

        go to the config and remove the base url and try again this will solve the problem

    • Rajith Wijepura

      Did anyone tried to login with invalid username password? This tutorial does not cover that section. Here what I did to inform the user about invalid login

      // login controller

      function validate_credential() {
      $this->load->model('membership_model');
      $queury = $this->membership_model->validate();

      if($queury) { // if user's credentials validated...
      $data = array (
      'username' => $this->input->post('username'),
      'is_logged_in' => TRUE,
      );

      $this->session->set_userdata($data);
      redirect('sites/members_area');
      } else {
      //$this->index();
      $data['error'] = 'Invalid Username or Password';
      $data['main_content'] = 'login_form';
      $this->load->view('includes/template', $data);
      }
      }

      // login_form view

      Login

      'username',
      'value' => '',
      'placeholder' => 'Username',
      ));
      echo form_password(array(
      'name' => 'password',
      'value' => '',
      'placeholder' => 'Password'
      ));
      echo form_submit('submit', 'Login');
      echo anchor('login/signup', 'Create Account');
      echo form_close();

      ?>

      <div id="login_error"

  • http://none Jay

    I am trying to use the above tutorial with the CI version 2.1.2
    However upon creating a user I am getting the below error. Any Suggestions?

    Fatal error: Class ‘Model’ not found in
    /home/*****/public_html/application/models/membership_model.php on line 3

    and line 3 of that file has this on it

    class Membership_model extends Model {

    • telsy

      it needs to be CI_Model

      so:

      class Site extends CI_Model
      {

      }

  • Nikki

    This might be stupid but for some reason my button does not change. I have followed the tutorial to the t.
    Is there a way to fix that?

  • http://www.unionics.com Sashikanta

    Thank You Guru Jeffrey Way.
    You found my Way.

    You’re the Guru! :)

  • Roy

    Hi!

    For this example I’ve got a input in a view:
    <input type="text" name="name" value="” />

    If the form is submitted it will run trought the form_validation in it’s controller. If it fails the value will be returned to the view. But if I fill in:
    “>It works!

    The result will be:
    It works!” />

    After the validation I see the H1! So it’s not escaping with htmlspecialchars or CI’s own function: html_escape.

    What’s the best solution to fix this and how do you fixed this?

    Just run it trought html_escape in the view, like: ?
    <input type="text" name="name" value="” />

    Thanks!

  • Marishka

    Hi! I just have a question, how will I be able to output the name of the user in the members area. i’m quite confused. i’m only able to echo the username because of this code:

    session->userdata(‘username’); ?>

    help please

  • Shiva

    video is not working, pls check

  • Mark

    I know this is an old thread but..

    I’ve autoloaded the session library but still getting this

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Site::$session

    Filename: controllers/site.php

    Line Number: 17

    Also having an error with the $query variable here:

    if($query == $this->membership_model->create_member())
    {
    $data['main_content'] = ‘signup_successful’;
    $this->load->view(‘includes/template’, $data);
    }
    else
    {
    $this->load->view(‘signup_form’);
    }

    It says it is not set.. :S

    • http://www.facebook.com/dynamdilshan Dilshan Gunasekara

      remove one equal sign from if condition / if($query = $this….)

  • hendra

    i cannot see the video

  • murum

    Is it only for me? The sound is not in sync with the screencast. Or can someone tell me how to fix it?

    EDIT: Works when I downloaded the video.

  • http://twitter.com/chilionsnoek Chilion Snoek

    Video works great here, tnx Jeffrey!
    In CI 2 instead of parent::Controller use parent::__construct

    Greatt!

  • Cristi

    Hey, I’m kind of new with Codeigniter. I saw in this tutorial that Jeff didn’t use the form_close method. It’s not necessary to use it, or how doest it work? Thank you!

  • abixalmon
  • Sanjay Maurya

    Hi All,

    I’m in last part where we delete cookie for ci_session. Whenever I test url: “http://localhost/CI/index.php/site/members_area”, I get both messages “access denied” and “members only” texts. I found that after deleting ci_session from cookie, it gets added when we hit “http://localhost/CI/index.php/site/members_area”. So I tweaked the codes as:

    session -> userdata('is_logged_in');

    if(!$is_logged)
    {
    $this->load->view('access_denied');
    $this->session->sess_destroy();
    }
    else
    {
    $this->load->view('members_area');
    }
    }
    }
    ?>

    In this case I get only one page “access denied” after deleting ci_session from cookie. I don’t get two pages messages. However I see that whenever hit “http://localhost/CI/index.php/site/members_area”, ci_session is always get added. I think it is added because I had auto loaded session library.

    Thanks,

    Sanjay Maurya

    • Sanjay Maurya

      Please note that this is code in site.php. I’m re-posting above code:

      session -> userdata(‘is_logged_in’);

      if(!$is_logged)
      {
      $this->load->view(‘access_denied’);
      $this->session->sess_destroy();
      }
      else
      {
      $this->load->view(‘members_area’);
      }
      }
      }
      ?>

  • zul

    Whay i cant install this ci_day6. i get many error. any body can help me?

  • http://www.facebook.com/Sagar.S.Shinde Sagar Subhash Shinde

    Again Satisfied with the Tutorials. Yay! m learning CI