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
  • Michael

    fantastic.. more codeigniter, love it!

  • Elijah
    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Hey Elijah – that’s an old out-dated tutorial.

  • http://vampa.org Alex Stomp

    I just made a complete CMS using Codeigniter..(http://chalkthemup.com) I LOVE IT! Keep writing these please, cause I’m sure there are so many possibilities with this framework I have yet to tap into.

    • crer

      Yes, we can even tell, by looking at those errors :)

      A PHP Error was encountered
      Severity: Notice
      Message: Undefined variable: l
      Filename: includes/latest_posts.php
      Line Number: 58
      A PHP Error was encountered
      Severity: Notice
      Message: Trying to get property of non-object
      Filename: includes/latest_posts.php
      Line Number: 58

    • V

      Your registration form needs better validation. I believe that it is hackable.

  • wburningham

    Great videos! I also noticed that you were using MacVim. I have recently switch to vim because of your vim tuts. A few quick questions:

    In video 1 when you were modifying the default welcome_message.php view, what were the commands you used to quickly delete all the styling from the sheet? Is there a special command to target that text or was it simple a delete using a range?

    What is the shortcut/snippet you used to create the echo “hi”; in video 1?

    Thanks in advance.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      @wburningham – Change Inner Tag — so put the cursor between the style tags, and type “cit”.

  • ionut

    Why don’t you use the session library from CI ?
    Also i don’t think you need to create your custom .htaccess just remove that index.php from config and leave it to ” and it will work with the default CI files.

    Thx for the tutorial

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Did they change it in CI 2.0? It always used to be that way.

      • Romz

        The Session class is available for long time : there is a lot of stuff to digg in (flash message, session data, etc). It could be interesting to include it in your next improved login tutorial ;)

        Anyway your tut is pretty clear and I love CI ;)

        ps: sorry for my school English

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        @Romz – I’m covering the session class in the next lesson. I was referring to the htaccess comment.

      • ionut

        Oh no sorry, my mistake, I just downloaded the CI 2.0.2 and it doesn’t have the .htaccess with the necessary config by default. I guess i added in my CI kit folder and i forgot about that.

      • Dale Rodgie

        I use the session class in CI and also store the session variables in the database on the web site. This prevents people hacking the cookies on their computer to gain access.

  • kankuro

    @Elijah: “Practice makes perfect” but nobody is perfect…

  • http://www.antonagestam.se/ Anton Agestam

    I had no clue the form validation class was such a goodiebag! Nice work there. What is the theme your using in vim?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Solarized

  • http://www.antonagestam.se/ Anton Agestam

    *you’re

  • Brad

    You can also use “$this->session->set_userdata($data)” at the end of your sign in approval

    I use it like this
    $this->load->model(‘signin’);
    $query = $this->signin->validate(); //this is the query from membership model checking the values

    if ($query) {
    $data = array(
    ‘name’ => $this->input->post(‘name’),
    ‘pass’ => hash(‘sha512′, $this->input->post(‘pass’)),
    ‘is_logged_in’ => true
    );

    $this->session->set_userdata($data); //this sets the session as true and the session name
    redirect(‘log/personal’);
    Seems a bit easier. I am still on codeigniter 1.7.3 so I dont know if thats changed in 2.0

    • http://www.antonagestam.se/ Anton Agestam

      I thought about that too, but I have not really found the session class that helpful. It doesn’t really create less code than just writing “raw” session variable actions.

  • Franklin

    It is a very good tut, it explains in an easy way how to make one of the most common things we as programmers should do, thank you jeffrey keep on doing this excellent job.

  • EmpreJorge

    Hey Jeffrey, why don’t you use the session library from CI ???

    I loved this tutorial. I already know how to do this, but it’s really nice to see how others do it.
    Thnx.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      I’m saving that for the follow-up, when we upgrade to using a DB for the session info.

  • Chris

    Just a quick note, instead of using

    You can use the following as long as the uri helper is loaded

    uri->uri_string()); ?>

  • K

    Good job Jeffrey on a quick and dirty demonstration of CodeIgniter’s capabilities.

    However you should really point out that you should not be using a session variable based system like that to a production website as it is incredibly insecure.

    Anyone could custom push fake session values especially emails – say that system was used in facebook you could log-in as anyone (whose email you knew) with a session editing firefox plugin.

    You should really be storing session numbers, ip’s, login time, last interaction time and login status in a db table where you can check against everytime protected content is accessed – control how many times a user is logged in concurrently and avoid simple email hacks (you could even store hashed session numbers if you are paranoid) etc.

    K.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Yep – absolutely. The next part will cover configuration options, and using a db for storing the session info. Great points.

    • John

      Personally, I think cookie based sessions are fine as long as they have some kind of hash to prevent tampering. Rails uses it by default because there’s no need to clean up after yourself in the database.

      That said, some of that other info certainly would make more sense being stored in the database.

    • RP2

      This is a great tut. Keep up the good work!

      Im new to codeigniter and am a little confused about the security of these sessions. Isnt the $_SESSION stored server side as its using the native PHP sessions? How can you push fake session values to this?

  • http://www.almoste.com Bhawan Virk

    Thanks Jeffrey for this great tutorial

  • http://www.educsis.com Edwin

    Awesome tutorial Jeffrey, as always, you rock!!! I have used the session class in CI, but it gives me a problem with IExplorer and when they try to login it doesn’t work, but this method works like a charm, keep up the good work. Thanks

  • Jan

    Hi!

    Great tutorial to refresh the Codeigniter basis.

    But I’m more impressed by the speed you write the code, using the editor shortcuts, snippets etc….it must save a lot of time doesn’t it? :)) Can imagine the advantage on a big project, perfect!
    I’ll have to learn some as well ;)

  • http://brianswebdesign.com Brian Temecula

    Nice for simple needs. I created a CI authentication system, and it is much more elaborate. It logs failed login attempts, supports multiple user levels, has user registration options, and a lot more. There are lots of CI auth systems, but I had to make mine so I could modify it or customize it easily. Check it out on Bitbucket:

    https://bitbucket.org/skunkbad/community-auth

  • kasakka

    Could we have the codeigniter tutorials as articles? I much prefer skimming for the relevant parts rather than watching a whole screencast go thru it. I mean screencasts are fine if you’re trying to show how to do something in Photoshop but we are dealing with code here, it’d be much easier just to read in article form.

    • http://www.lamecarlate.net AkaiKen

      I strongly agree with you, kasakka ! Personnaly I read faster than I talk, so it may be a gain of time.

    • posaka

      I’d have to disagree. I think that screencasts are an excellent way to follow along.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      I think it’s good to offer both formats. But I gotta be honest, for tutorials like this, it’s really difficult to write them. When you’re switching to a different file every paragraph, it can be tough to follow along.

  • http://blog.jesusyepes.com chux

    Haven’s use codeigniter since 6 months, but i have loved it. You can make some screencast talking about Yii

  • http://www.caiobianchi.com Caio

    Jeffrey,
    Congrats on the tutorial! One question though: always when I want my url relative to the root (“logout” case) I’ll have to specify on the routes.php file? Let’s say I want to show “home.php” view, the url by default will be “codeigniter_folder/admin/home”…. how can I make all the views relative to the root?

  • http://blacquebox.net Fiqhi

    Hi, Jeffrey.. nice tutorial ;)

    I have a question for you.. Why you don’t use $this->db->free_result() after you fetch data in admin_model?

    does it not affected to the performance of the application?

  • Mfawa Alfred Onen

    Jefferey, You never fail to impress…You rock and Nice Tutorials. Keep it up…

  • http://www.maxrosecollins.com Max Rose-Collins

    Excellent tutorial.

    Just what i need right now!

    Max

  • http://www.lastrose.com LastRose

    Personally I use Ion-Auth. Saves a lot of time whenever I need an auth library. Took a while to get it working right, but now that I have it working right, I just copy that working bit around to my new projects. Non the less, Great Tutorial!

  • Kamran

    May be it’s a silly question :), but where is the form_validation library itself?

  • http://jaimievansanten.nl Jaimie van Santen

    Anyone else having troubles pausing or skipping to a certain time in the video? Using latest Chrome.

  • Dionisis

    Hey Jeffrey, Whu didn’t you use the session library as before? I think it’s safer than native php sessions

  • Dionisis

    Hey Jeffrey, Why didn’t you use the session library as before? I think it’s safer than native php sessions

  • http://www.jchvelasco.com james

    Hi Sir Jeffrey Way, nice tutorials, I’ve been following your series since day 1, what CI version is used in this tutorial?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      2.0

  • marhnix

    From CI user guide : “The CI_Session class stores session information for each user as serialized (and optionally encrypted) data in a cookie” … cookies are too small sometimes.

    I prefer using this http://codeigniter.com/wiki/Native_session/
    Native Session with CI syntax.

    • Dionisis

      If i need more space i store the session into the database using CI session library. I think it is more consistent and safer, It might be a little bit slower but CI is from its nature fast enough

  • Andres

    It would be great an article on best MVC practices for codeigniter,
    before nettuts I wouldnt come near a php framework, now I use it in most projects that fits,
    keep’em coming Jeffrey!

  • http://builtbyprime.com Matt Gaidica

    Great video, I think it handles the basics well (Authentication can drag on!). However, I do agree that using the CI session class has some advantages, and without mention of that a login system is open to a lot of security holes. The big one would be using encrypted cookies, and on from there would be setting proper expirations, etc.

  • http://www.carlosja.com CarlosJa

    Yeah CodeIgniter is pretty cool; I’m just getting into the PHP Frameworks. I love the tutorials on this website.
    Thanks!

  • Thiago A.

    Hi Jeffrey,

    What auto close plugin are you using in vim? I’m frustrated with every one I could find. And what snippets plugin?

  • http://newarts.at Drazen Mokic

    Arr i like CI, ncie to see some Tuts on it again.

    Btw: Why are the videos are now embeded from youtube? This 30 sec Ads are so damn annoying from blip.tv ;/

    • http://newarts.at Drazen Mokic

      Wanted to say ” Why are the videos are NOT embeded from youtube”..

  • http://blog.streambur.se/ Erik Brännström

    Hi! I’m always a fan of a good screencast, however, with the risk of sounding like an asshole, I would like to point out two things. First of all, SHA1 is not an encryption and especially not a powerful one. It is a hashing algorithm, built to quickly produce text digests of fixed length from variable sized text. This is more or less semantics, one could argue, but I believe it is important to make the distinction.

    Secondly, and perhaps more importantly, SHA1 is not appropriate for storing passwords. As mentioned, it is fast. Too fast. I could brute-force a hash of a six-letter, lower case password (yes, it’s weak, but people tend to use weak passwords) in less than half an hour on my three year old laptop. At the very least, you should use salting, preferably both one unique for each user and one global for the application, and do an iteration of hashes, or even better use bcrypt.

    If you deemed this to low-level for a tutorial such as this one, perhaps you can at least mention that it is not a secure way to store user credentials and that developers are encouraged to read into it. Just my two cents!

  • chris

    Nice tut,

    Also how did you get your MacVim to look like that?

  • Shadow

    Nice tutorial.

    Surprised you never used the Session class, which is much, much better, and more secure :)

    Nice simple tutorial anyway.

    • http://brianswebdesign.com Brian Temecula

      With the exception of flash sessions, I really hate the CI session class. It shouldn’t even be called session, because it’s not a true PHP session. PHP sessions and cookies behave differently. Without redirects or javascript, there’s no way to duplicate true session behavior with a cookie, which is what CI sessions are.

  • Haso

    Jeff is wrong.

    You do not create a Library for repeatative functions you create a core controller MY_Controller which extends CI_Controller.

    I think that is more appropriate.

    Also he is using $_SESSION[] in CI you should continue doing it the $this->session->userdata(); way.

  • Roark

    Great Tutorial Jeffrey keep them coming!

    I Came across an issue when you enable csrf_protection in appliocation/config.php and you ‘hand code’ your own forms you will need to add a field that would be inserted automatically if you used the form helper…

    <input type=”hidden” name=”<?php echo $this->security->get_csrf_token_name()?>” value=”<?php echo $this->security->get_csrf_hash()?>” />

    extra tip:
    If you are using axax for any form submitions, remember to send this ‘name-value’ pair too. else you may run into trouble

  • http://www.alexgenovese.it Alex

    Hello,
    I’m a cakephp developer I would like to know if is it possibile, in the latest version of CodeIgniter, to generate automatically the backend code.

    Thanks!

  • http://www.umbraprojekt.pl mingos

    Jeff, you’re obviously big on CodeIgniter – so many good tuts, evn recognised by the CI team (there are links to them in CI’s video tuts section, after all ;)). It’s great you decided to get back to it and make more tuts for CI 2.0. Thanks for that.

    But what about other frameworks? I’m a Zend Framework guy, for instance, yet all I’ve seen about it on NetTuts+ was a premium tutorial (well, I saw its title, anyway, since I’m not a premium member) about setting up Zend Framework. Is anything about other frameworks planned?

  • Adam

    I’ve been writing an auth class library for CI and overall it’s been working but had a few problems with it thus far.

    I basically watched the video and have written from there.

    My main problem is has been grabbing the name of the controller you were on when you attempting access, and to redirect to login with the name in order to return you to where you were.

    I load the library class as an automatically running library, this removes the requirement to set /login as the primary app controller. Is this the best way to do it? as i can check ‘if logged in’ in the constructor.

    My primary focus here is to write a class which can essentially be added into any code igniter app, and you can configure it to either always require them to be logged in, or simply make it so they need to login when required/click ‘login and redirect to members area’.

    I figure the class based library is the best option.. would that be correct?

  • http://www.kaasper.com Kasper Kismul

    Love your codeigniter tutorials, you should do more of them! :)

    Thanks alot for showing us this great php framework.

  • http://www.thestreamingbible.com Chris

    Horrible Tut. The author took NO time to actually describe what he was doing or why. To the average developer who’s never used codeigniter (or briefly) all the would see and hear is a a lot of fast talking and very fast screen displays.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Exactly, Chris. These two videos aren’t for beginners. That’s why I recommended the CodeIgniter from Scratch series at the very beginning of the video. This is for slightly more advanced users. Try to be a nicer person next time.

      • Roy

        Hey Jeffrey,

        You have already talked about the “CodeIgniter from scratch”, so.. you made this session on CodeIgniter 1.7 and I guess there are differences between now (2.0.2) and 1.7. Can you create tutorial about the new / changes on CodeIgniter v.2? I started with the lesson #1 and I found that some things didn’t work well.

        By the way, as a begginer who has never used CodeIgniter I understood each step you did on this tutorial. thank you.

    • Ran

      hey jeff .. Great job !! :)
      I’m extremely new to codeIgniter, and for me those tutorials are really worthy.. i mean it :)
      I’m really grateful, those two parts were my first screencasts..
      very clear and helpful .. and they took me back to day1.. I can’t stop “googling” your tutorials ;)

      it’s my pleasure to consider my self as your student..
      Go on man .. best wishes

      “Sorry for the bad english ;) “

  • billmc

    Why not just use a hook to check for authentication before loading a page?

  • Fred

    The tutorial is pretty good
    but I would like to add “remember me”
    and “forgotten password” ?

    Can you show us how to do it???

  • frank

    Thank u so much jeffrey u r the best

  • Lane

    Awesome tutorial as is the series you did on Codeigniter from scratch. I would be interested to learn how to set an error message on the login screen if user input passes form validation, but is not found in the database. Keep up the good work!

  • Vamsi

    Not bad at all :)
    But I was hoping that you will cover writing a library aswell :)