Easy Authentication with CodeIgniter
videos

Easy Authentication with CodeIgniter

Tutorial Details
  • Difficulty: Intermediate
  • Completion Time: 30 Minutes

In this in depth “screencast of the week,” I’ll take you through the process of building an authentication system with CodeIgniter. Need to restrict access to certain parts of your website to only those who’ve logged in? This tutorial will teach you how!


You’ll Learn About:

  • The form helper
  • The form validation library
  • Sessions
  • CodeIgniter best practices
  • Authentication
  • Active record
  • Working with MySQL databases

Part 1

Press the HD button for a clearer picture.
Subscribe to our YouTube and Blip.tv channels to watch more screencasts.

Part 2

Press the HD button for a clearer picture.
Subscribe to our YouTube and Blip.tv channels to watch more screencasts.

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

    Hi Jeffrey, Thanks for a great article..!

    Don’t want to be a nag but I think it is smarter for the logout function to do a
    $this->index();
    instead of a
    $this->load->view(‘login_view’);

    so if you want to add stuff to do controller (let’s say more views) or change something (let’s say the name of your login view file) you only need to write it in one place.

    Thanks again!

    Amos

    • mcrk

      the smartest thing is always to redirect after making login and logout stuff.. this protects You from post reload problems.. assuming that You use post also to logout, which You should.. :)

    • Ben

      You can always use the php redirect function to redirect the user to your home page, ie redirect(”);

  • http://www.elrafael.net Rafael

    Gr8!

    Only one thing:

    CI has a helper called security that does the same of sha1()
    Eg:

    $this->load->helper(‘security’);
    $password = do_hash( $this->input->post(‘password’, TRUE) );
    //Or with md5 instead sha1 ;)
    $password = do_hash( $this->input->post(‘password’, TRUE), ‘md5′ );

  • http://www.blueminded.co blueminded

    Excellent tutorial.

    Code Igniter is really awesome, I don’t know how I could live without it. Hehehe.

    By the way, which is that software you use to code, It looks great to work.

    Best Regards.

    • Josh

      I believe he is using Mac VIM which btw VIM is one of the greatest text editors ever created…. once you get use to it.

  • http://jeroenransijn.nl Jeroen Ransijn

    This tutorials are significantly helpful, currently implementing a similar system based upon this tutorials. Though I have a tiny question.

    if ( $this-&gtform_validation-&gtrun() !== false )

    Couldn’t that be just:

    if ( $this-&gtform_validation-&gtrun() )

    The expression should evaluate TRUE, and that is exactly what a ‘if’ statement does, seems to me that you are overcomplicating it using ‘!== false’.

    To be honest I skimmed through the videos, so you might have explained it in there.

    • http://jeroenransijn.nl Jeroen Ransijn

      Oops, sorry for the inconvience, the code above should be this:

      if ( $this->form_validation->run() !== false )

      Couldn’t that be just:

      if ( $this->form_validation->run() )

  • wilson

    great job man!
    I heard about code igniter, cake and others but I never imagined that was so ease, you just need to know maybe classes and methods, thanks so mucho hope you could post more tutorials like this

  • Eric Sunny

    Nice tutorial!

    One thing liked to mention, that the session in this case could be codeigniter session as guys said before, but if you test this login system different ways you will discover that, sometimes you have to login twice, and sometimes when you logout session still remains and with pressing back you can access welcome page. With different browsers you can get different results.

    Solution of this is to add trigger page that will reset session data, and only them redirects to index.php

  • http://gzone.com ibrahim abubakar sediq

    a very nice tutorial just gonna apply it to my own project

  • http://www.sagalbot.com Jeff

    Thanks for the updated tut Jeffrey. I went through the older one earlier today. Happy to see that most of the things learned in the first version are still the best practice.

    I’m Wondering why you manually set the session rather than using the built in CodeIgniter session functions?

    On a side note, I prefer the video tuts where you aren’t using MacVim. Just a little easier to follow. I like to code while I watch, and you are just way too fast with MacVim. Looks like something I need to learn, I can’t keep up in Coda.

  • binngo

    hello everybody. I can’t watch these video, Why

  • http://nettuts.blip.tv blip.tv Links Messed Up

    The blip.tv links are messed up…it’s linking to…

    http://http//nettuts.blip.tv

    …instead of…

    http://nettuts.blip.tv

    …the http:// is doubled…(I don’t know if that will come thru the comments correctly {why no Preview?}, but check all the blip.tv links on this page).

    • http://nettuts.blip.tv blip.tv Links STILL Messed Up

      Some one decided to fix ONE of the above links to nettuts.blip.tv…but missed 100 others, including the 2nd one on this page…

      Google: “Subscribe to our YouTube and Blip.tv channels to watch more screencasts.” site:tutsplus.com

      http://google.com/search?q=%22Subscribe+to+our+YouTube+and+Blip.tv+channels+to+watch+more+screencasts.%22+site%3Atutsplus.com

      I have no idea if that URL will display correctly, so just paste that into Google & fix all those pages…or better yet, put that code in a template (dare I say: a CodeIgniter view?) & fix it in once place.

      You could also just grep the entire site’s files for “http://http//nettuts.blip.tv”.

  • CodeIgniter User

    Jeffrey Way: Why /did/ you stop in the middle of the CI from Scratch Tuts before?

    Can I suggest that you make a Tutorial, that includes everything, no matter how long it ends up being?…

    * Include the CodeIgniter Setup
    * Remove the index.php 1st (why is that not default?)
    * Instead of fixing the errors before they happen, reload the page, show the error & how you fix it. (You did some of that in this Tut, but do more {if I’m coding, I reload often & then have to fix error msgs})
    * Reload from the site root more…for example, you were in the Admin controller & never showed what happened when loading the site root.
    * Show the CSS to make it look good (or at least paste it)

    …I know you skip the CSS, cuz we can all style it the way we want, but I think it would be more complete…& look better, if you showed some CSS (more than display: block) that made the Login page look like a real Login page would look.

    Basically go “from scratch” to “something nice”…something you would really see on a website.

    How do you decide where to put each Tut? I don’t think there are any of your CodeIgniter Tuts on YouTube, just on blip.tv?

    Do you have any website where you actually /use/ CodeIgniter? I don’t think net.tutsplus.com uses it, does it?

    When did you switch to MacVim?

    tests(biu[b]b[/b][i]i[/i][u]u[/u])

  • http://hurlbrinks-haus.de Hurlbrink

    It really makes sense, that a “min_length” does not imply a “required”. So you can make optional fields, which – if the user fills them out – should have a minimum length.

    For example the user should decide, if he wants to post a zip code. If he does not want to, ist is quite ok. But if he wants to, only zip codes containing at leasts five digits (or another number, depending on the user’s home country) can be submitted.

    Regards from Germany,
    F. Hurlbrink

  • http://characterforge.com Salman Munawar

    These tutorial are very helpful. Thank you so much ;)

  • http://mjphelps.x10.mx Michael Phelps

    Great tut as always Jeff. I just finished your AJAX Validation, and while going through CI from scratch, I decided to tackle this one just for S&Gs :)

    One issue I have is with the CSRF protection in the config. I’ve tried a couple workarounds that I’ve found on the net, namely adding a hidden form field from scratch

    &ltinput type=”hidden” name=”&lt?php echo $this-&gtsecurity-&gtget_csrf_token_name()?&gt” value=”$lt?php echo $this-&gtsecurity-&gtget_csrf_hash()?&gt” /&gt

    But it just throws an error “The Action you have requested is not allowed”

    Once I turned off CSRF protection it worked great. Luckily this is on a local dev machine as I learn, so there’s no security risk, but if I were to take this live for whatever reason, it would open that vulnerability.

    • http://mjphelps.x10.mx Michael Phelps

      Bah, forgot to add the ; in the string replacements

  • ian

    Thanks for the great super fast kick ass tut Jeffery!

    I have gotten into some setup habbits. With the latest version it errors out as soon as you load the database library if you haven’t put in the database credentials so I do that first along with setting
    .htaccess and web.config (IIS compatible but ignored by apache and visa versa)
    config: base url, no index, encryption key, cookie encryption, xss, and csrf
    routes: default controller

    It takes less than a minute to set all of that before going to the url for the first time and so far I haven’t had any issues.

    I have a question though about autoloading.

    Does it make a performance issue to have everything loaded in config and are there cases where it’s better to wait till a lib or helper is needed and load it on the fly?

    I think I’ll use the profiler since I just learned how to use it from Burak and see if there is a loading time difference.

    Thanks again!

    I’d recommend to everyone as related tuts, the codeigniter from scratch series has tuts that when combined with this one give a really well rounded understanding of registration, login, forms, and extending libraries. It’s using an older version of CI so there are a couple of syntax changes but they are posted in the comments.

  • http://haezal.blogspot.com Haezal

    Good Simple Tutorials.
    Thank!!

  • http://johnt.biz john

    Excellent tutorial, thank you Jeffrey.

  • zahid

    your tutorials are awesome… i have learn alot from it..in the login process i have gone through all very well but after putting current email and passoword it is not redirecting to the member area page ..

    please help me .

    i will wait for your prompt reply

  • Lenny

    save 1/2 the space when you store the hash….use the true parameter!
    echo (sha1($n,true));

  • http://www.botaiusti.com Iusty

    I saw that you use routes file to remove index.php from url, I have a qustion, it’s posibil to create a fake subdomain, that act like in this example:
    http://www.domain.tld/dashboard/project to http://www.name.domain.tld/dashboard/preject

    the name sholud be the name of the user(or some fild from database)
    If somebody now how to make this i’ll be grateful if share

  • Jongosi

    Help! This breaks for me on Code Igniter v 2.1.0.

    On part 2, as soon as I add the session start bit (6:25 roughly), I get an error. Adding the parent::__construct does not work. Any ideas would be great for a newbie!

    Thanks!

  • Ryan

    Great tutorial!!!
    However, I am getting error message when I load the page.
    Why is that?

    • http://avenir.ro Adrian Voicu

      Well… it seems that this tutorial is a bit outdated, because Codeigniter handles sessions differently now. So, if you want to do the login form you must store session data in a different way:

      1. In admin.php, where you store the session data you must write:

      $this->session->set_userdata(‘username’,$this->input->post(‘email_address’));

      2. In welcome.php, where you verify if the session data is set, you must write:

      $session_user = $this->session->userdata(‘username’);
      if(!isset($session_user) || ($session_user==”))
      {
      redirect(‘admin’);
      }

      3. In logout action from admin.php, you must write:

      public function logout()
      {
      $this->session->unset_userdata(‘username’);
      //unset($_SESSION['username']);
      $this->session->sess_destroy();
      $this->load->view(‘view_login’);
      }

      • http://avenir.ro Adrian Voicu

        By the way. Thank you for your great tutorials :)

  • Kasun

    great!. thanks :)

  • http://workshop200.com cmd

    Great video Jeffrey! The task was boring but I like additional comments about CI. Tnx a lot!

  • http://morointeractive.com Jeff Moro

    Appreciate this. Needed some help with a problem and this gave me the answer.

  • Trey

    I’ve been through a number of these CI authentication and this is by far my favorite. Quick, straight forward, remarkably clear, and incredibly helpful. Thanks so much for posting!

  • anjali

    I’m using Tank Auth
    and my project will support two access type: “normal user” and “admin”.
    I looked at the tank auth database and there is a “isadmin” field, so I
    believe that it’s possible redirect to /admin or /user when I log in to my system.

    How can I do this?

  • anjali

    I’m using Tank Auth
    and my project will support two access type: “normal user” and “admin”.
    how to differentiate between the user. when user login the user page should be loaded and when admin login admin page

    How can I do this?

  • Dharmesh

    Hi Jeffery, thanks for the tutorial. It was really good one. I was wondering if you could help me to implement Remember me button. Thanks in advance :)

  • phokki

    Dammnnnn… This was really good to follow, really interesting. I’m using CodeIgniter for a school project and I am new to it, so this really helped me! Thanks (: