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

    Wonderful. That was a great tutorial, Jeff!
    I loved how many things you covered and I didn’t mind the the video being longer than usual.

    100 Kudos

  • Mike Randall

    Wonderful. That was a great tutorial, Jeff!
    I loved how many things you covered and I didn’t mind the the video being longer than usual.

    100 Kudos

  • Nouman

    Hey Jeff, question about the last 5 mins ( i had it until then X) )

    when you are validating the user session, the link is too: (under login.php)

    redirect(‘site/members_area’);

    However, isn’t going directly to members_area function on site.php skipping the

    is_logged_in()

    function? Which results in the view being loaded regardless.

    When I set

    redirect(‘site/is_logged_in’); and add $this->members_area(); to the end of that function it works, but you can still visit the memebrs_area directly

    still a little confused haha

    • Nouman

      I got it figured out :)

      • http://krswebsolutions@gmail.com Kevin

        What was the problem?

    • Dave

      (for anyone that is confused)

      “However, isn’t going directly to members_area function on site.php skipping the ‘is_logged_in()’ function? Which results in the view being loaded regardless.”

      No, because we called the “is_logged_in” function in the construct…

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

      • Pete

        Hi, how can we find the solution to this problem. Since I am getting the same. The Last 5 minutes, in is_logged_in, still shows the members area data, And also a message about No permission.

        What can we do that it does not show the members area.
        I have noted that if, we echo out directly from the is_logged_in function, it does NOT show the members area, however, if we load a view and then try to restrict access to non logged users, it displays the members area.

        Can anyone help. Really Appreciate. Jeff you are great! and so are all the people offering help an support in this section.

        Cheers
        Pete

  • http://www.manocreative.com/ Manuel Pineault

    Just ran through this tutorial at 3am in the morning. It was definitely worth it! :D

    Thank you again! ..and now for sleep.

  • http://cmstutorials.org krike

    for all those who want to check if the username was allready taken or allready exist you can add your own form validation for unique values.

    it’s the 3rd hack in that post which will help you check if the username was taken or not.

    http://www.neurosoftware.ro/programming-blog/facebook-web-design/web-resources/6-codeigniter-hacks-for-the-masters/

    I have tested this, it works perfectly and saves you a lot of trouble

    • http://codemonkeys.biz Kris

      That link redirected me to what seems to be a malware site without warning and would not let me back to the original page to view the info. I had to exit that browser window, disable javascript and then come back just to get to the page. XSS anyone?

    • Matthisk

      Hey,

      thnx alot for this it works great for me, really helpful.

      Matthisk

  • Ko

    Bad video! Pls post a new link

  • guy

    Thanks a lot Jeffrey!
    I’ve just started a new project with CI and this tutorial has helped me so much. I now understand much more the basics in CI and I have deepen some of my knowledge in php.

    Keep up the good work!

  • Diegop

    Excellent login screencast Jeffrey
    Thanks so much

    …Applause :)

    This is one of the best tutorials I saw, please continue with more Sessions and CRUD of CI

  • Chris Men

    It’s an amazing tutorial! Just a few questions:
    If I wanna use this in a real project, what I have to change about security? I mean, what should I re-code to code and database be safety against hacking and protect data? Because codeigniter 1.7.2 doesn’t have any good auth and I wanna create mine, but I have some doubts about security.
    Thank you for your help :)

  • Jazzman

    I’m new to CodeIgniter, in fact, I’m not a programmer. I can echo a few things here and there, but I must say your tutorials are making a lot of sense to me.

    I truly thank you for that brother.

  • DavidSwede

    Hi great tutorial! I’m doing an internship and these videotuts are a great help solving my assignment.

    I’m having a slight problem thow…

    When I hit the logout-link in the members_area-view I get redirected back to the login_view, as I should. But then: when I hit the backbutton in the browser I’m still able to acces the members_area. I’m wondering if anybody knows how to prevent this?

    • Dave

      It’s from your browser cache, so I don’t think there is anything that can be done server-side (short of replacing the CI session library with something else and seeing how it does)

      Realistically though, they were already authorized to view what was cached in their browser and thus it’s not a big security risk. If they’re truly logged out, when they click anything it’ll just knock them to the unauthorized access page anyways (I just tested it as you described and reloading “members_area” results in this).

  • rick

    hey jeff,
    can u make a tutorial with email confirmation?

    i tried creating one but i always ended in ‘PAGE NOT FOUND’ error

    thanks.. btw.. nice vid

  • Alberto

    Ey, If I go directly into /application/views/members_area.php I can see the page without being logged.

    Is this a security issue or did I forget to include something?…

    thks, keep up the good work!

    • Dave

      Great point – I didn’t stop to think about that myself quite yet! Put this at the top of your views:

      Another alternative is to move the application folder below the web root folder so they can’t be accessed directly; that is, except for index.php, where you change ‘$application_folder = “application”;’ to ‘$application_folder = “../application”;’ or where ever you put it. You can do the same thing with the system folder, too (which realistically should be named “CodeIgniter_1.7.2″ or whatever the version is so you can quickly change between different CI versions as they come out). Just remember to update index.php.

      I did notice, however, that most pages that have any CI functions in them (like anchor) will result in fatal errors and the potential hacker is left with nothing particularly interesting. For instance, “members_only.php” says “Fatal error: Call to undefined function anchor() in /var/www/CI/application/views/members_area.php on line 18″ – I can see how someone would rather not give the chance to some nosey dork to mosey around where they’re not wanted, though :)

    • JuiceBox

      Just put this line at the top of the members_area.php file:

  • http://gravityfx.org/ emcgfx
  • Dave

    Thanks once again Jeff. Thoroughly enjoying your tutorials. This one was a little long, but its a huge help :) Definitely gives me a good code base in which to refer to in the future as I get my feet wet with CodeIgniter.

  • Kevin

    This is CRAP and the WHOLE consept is nothing but crap. All the tutorials suck and nothing works the way you make it seem like in the tutorial. I tried it and it just loads a blank page. Why not make something that easier for the brginner.

  • http://kuklastudios.com Steve

    Hi all,

    First, Jeff, thanks so much for these tutorials on codeigniter. I’d just like to say that I really appreciate the work you’re doing, and that your tutorials are very easy to follow.

    I have a question related to one which has already been asked, but not suitably answered (at least for me!) I’m hoping someone can offer some help!

    At the moment, the is_logged_in() function is the following:

    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’);
    }
    }

    The tutorial says that we shouldn’t echo things directly from a controller, they should be done with a view. So, I did the following, using the template:

    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'] = ‘no_permission’;
    $this->load->view(‘includes/template’, $data);
    }
    }

    To test, if I login, then logout, clear cookies and try to access my members area, I get the no permission view as I’d expect. However, right beneath that, I get the members area stuff even though I’m not logged in. Can anyone offer some knowledge as to why this happens?

    Thanks very much,
    SK

    • Frank Miller

      I had the same issue as Steve. Any suggestions anyone?

      • Frank Miller

        I really don’t know if this is the right way to solve this problem but i figured out a working solution. You could put an additional die(); function within the “forbidden” view. Something like this…

        Forbidden!
        Please Login or Signup to view this page.

        Works for me but don’t know why?!

      • http://ashpointlane.com Angst

        I had the exact same problem and I fixed it by adding the die() function as shown below:

        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();
        }
        }

      • Jay

        Hi!

        For me, this doesnt work when loading the the view first then followed by die. It will return a blank space, no source returned.

        But if we remove die here. The function of method that I am calling from the URI which is site/members_area, will give me the login view and at the same time, the members_area view.

        Redirect as I commented on the code below works but I dont need this. I want that everytime a user calls any function within the members area will pass through this and view the login if session expired already then after a user logged in, then I can redirect him to the exact page that he is requesting. Not on the index page of the members area.

        I hope you´ve got what I mean…

        function __construct()
        {
        parent::Controller();
        if (!$this->session->userdata(‘is_logged_in’)) {
        $this->load->view(‘login_form’);
        die();
        //redirect(‘/login/index’); This works….
        }//else continue
        }

    • http://ryangiglio.com Ryan Giglio

      I’m having this problem too. I understand what’s going on, but I’m not sure of a solution.

      When the is_logged_in() function runs during the constructor, the check fails and it loads the “no_permission” view. However after is_logged_in() is finished, and the constructor is therefor finished, the page goes on to run members_area() because that’s the page you navigated to in the first place. Loading one view doesn’t stop us from loading another view.

      It would make sense to put a die() after we load the no_permission view, except that just causes me a blank screen and I’m not sure why.

      I don’t want to stick a die() in the no_permission view for MVC reasons.

      Anyone?

  • http://www.popstencil.com Danete

    humm, it’s down. Would appreciate if someone could fix this, please.

  • http://www.neilrpearce.co.uk neil

    Great tutorial, up until i hit a snag!

    Instead of being redirected to the ‘site/members_area’ i get redirected to ‘login/validate_credentials’? In fact it goes straight to it regardless of what i put into the login form? A noob i know but i really can’t seem to figure it out.

    Can anyone help?

    • http://www.wearecondiment.com Chris

      Neil, I’m also new to this. But perhaps it’s a typo in your redirect line? The last line of your validate_credentials() function should read:

      redirect(‘site/members_area’);

  • mat

    thank you jeffre-way
    but how to send a email confirmation?
    or when the user forgot their password?

  • laanes

    When I click register it goes – http://localhost/index.php/localhost/index.php/login/signup

    and when I click login it goes http://localhost/index.php/localhost/index.php/login/validate_credentials

    Why is it loading localhost/index.php twice?

  • http://www.doingtheartwork.com mishu

    f*!K quicktime man, please convert this it’s not working :((

  • http://www.doingtheartwork.com mishu

    Hi man,
    What you forgot to do is check if the username (or/and email address) already exist in the database

  • Gibon

    Hi,

    nice tutorial,

    can you help me with converting this login system into multi-level login system?

    ( separate areas for admin, moderator, user levels )

    Thanks !

  • beginner

    hello,

    can anybody check the video link please ?
    I couldn’t watch it and I would like to see this part if its possible.

    thank you.

  • http://cameronlockey.com Cameron

    Loved this tutorial. By now I’m getting to where I can wrap my brain around CodeIgniter with your help!

  • http://www.dcservice.nl/ Duco

    Thanks Jeff!! I now know the basics of making a loginscript. Love to see more of your tutorials!

    Greetings from The Netherlands

  • Eoghan

    A terrific tutorial, you explain things so well, thanks Jeff.

  • http://thatryan.com Ryan

    Great tutorial Jeff, as always. I was able to follow and build it. But I got lost trying to call the template made the very last view when you get to the ‘logged in area’. I was trying to keep the styling going. But it is also off another controller, (site instead of login) so does each one need its own ‘template’?

    I also was trying to output the data entered during ‘singup’ but don’t have access to it? Would it require a db call each time? Trying to mimic the call like on the login_form like this,

    $data['main_content'] = 'logged_in_area';
    $this->load->view('includes/template',$data);
    

    which obviously didn’t work :) Can ya point me in a direction on this at all? Thanks!

  • http://www.code.my devlim

    Great tutorial however, in this tutorial, u check whether the user login in the site controller constructor, so does that mean i need to check in every controller constructor which requirement user login? is there any better way do to this.

  • Franklin

    Hi man, thank you for making the videos.

    I have a question, I do not know why I get this error when I try to run the login

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: a

    Filename: includes/template.php

    Line Number: 7
    An Error Was Encountered

    Unable to load the requested file: .php

    I really do not know why man, I tried renaming the files but it doesn’t work for me but if I specify directly in the template the .php file it works, like this load->view(‘includes/login_form’); ?>

    I’m new in this so if you can help i will aprecciate it

  • http://fictionalbeer.wordpress.com Joe

    Thanks so much! This tutorial has really, really helped. I feel like I have a site worth showing someone now.

    Can anyone tell me how to make a normal link look like the ‘Login’ or ‘Create Account’ buttons? I’d like some of my navigation links to look like this.

  • http://fictionalbeer.wordpress.com Joe

    Wow. Just realized what an idiot I am.
    The ‘Create Account’ button isn’t a button. It’s just a link. D’oh!

  • xeon9

    and also what CSS editor he is using???

    • http://fictionalbeer.wordpress.com Joe

      I believe he was just using a CSS editor add-on in Firefox. It updates CSS in real time, but doesn’t save anything to the web server. So you just copy & paste what’s in the CSS sidebar into your text editor & then save to the server.

      I use Web Developer toolbar which does this & several other things. I love its option to highlight css elements as you mouse over them.

  • http://pit-egypt.com Mohammed

    HI Jeff ,
    Great tutorial
    in bast I love To develop my Own Class bout when i see $this->tut i Love working With FW
    bout i have note that
    debuging in codeigniter mean that i must read all my Work … is that TRUE?

  • Dionisis

    hi! that was a great tut!! well done, So i have an issue with the css file.

    Usually when i start a project a create a new virtual host like new_site.loc.

    When i use this to find the style.css
    <link rel="stylesheet" href="css/style.css” type=”text/css” media=”screen”/>

    it doesn’t load and if i click the link at the view source page it says “The page you requested was not found.” Like Jeffrey i get the application out of system folder.

    what shoud i do?

    thanks in advance.

  • Korky

    Jeff,

    Am I correct in saying that it really doesn’t matter where some of these logic pieces go, as long as they are referenced properly in the code?

    For instance, you chose to put most every controller function in login.php. Then when it came to displaying the “Members Only” info you chose to create site.php and display that members area view in that controller. Theoretically this shouldn’t matter right?

    Maybe you’ll get to this later, but if you are writing a multi-page site, wouldn’t you pretty much create sub-folders in each of the controllers, models and view directories corresponding to your pages? So if you had an About Us page and a Contact Us page, would you typically create a sub-folder in each of the master folders called aboutus and contactus:

    application–>Controllers–>aboutus–>[controller files]

    application–>Models–>aboutus–>[model files]

    application–>Views–>aboutus–>[view files]

    Is there a “best practice” here?

    • Korky

      Also, I took your suggestion to eliminate the echo in that last part, and instead load a view name “invalid_credentials”

      So my site.php is_logged in looks like:

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

      if(!isset($is_logged_in) || $is_logged_in != TRUE) {
      $this->load->view(‘invalid_credentials’);
      } else {
      return;
      }
      }

      then the “invalid_credentials” looks like:

      <?php
      echo ' You do not have valid credentials to access this page.’;
      echo anchor(‘login’, ‘Back to Login Page’);
      die();

      Now, notice that I had to put the “die” command there. If I don’t, the flow passes through somehow to the members_area view and shows that after it shows the “Invalid Credentials” at the top of the page.

      I’m not seeing how that got to site/members_area at all.

      Can anyone help?

  • http://www.thdyoung.com/scrapbook Tom

    thanks Jeff

    that was terrific

  • http://www.pdm.cl Alberto

    Thanks a lot Jeffrey, that was a great tutorial, now I’m heading up to Day 7: Pagination.

    Keep up the good work!
    A.

  • neerose

    thanks for the tutorial

    i am having this problem with this program, it works really slow. whats the problem??? does anyone have any idea???

    neerose

  • Kars

    For me the most boring one so far :P but that’s because I don’t work with login forms and and user verification often. I had a question about best practise for PHP. Is it good or bad to use the shorttags <?= instead of <?php echo , when I just want to echo online line or variable?

  • http://maxstudener.com Maxmillian

    When i am using a site template how do i change the title for each page?

    im thinking passing an array of all the data i wanna change/add, such as title, add more stylesheet, js scripts

  • http://wwww.theoldskoolblog.com Gunjan Jaswal

    Thanks for the tutorial… It made using codigniter very easy for me :)

    Thanks a lot! :)

    It was very helpful!

  • Quynh

    Thanks a lot for the tutorial Jeff. I love all of your videos so far, keep it up! In fact, I do feel like a ninja after I went through your css noob to ninja series and 6 days of code igniter training. to be honest, for a loooong time I have always wanted to get into web development but I hate how complicated php was and most of the tutorial online is non oop oriented. As a java/vb desktop application coder, I found it somehow pretty hard to get the grasp of php coding style for some reason. Then I discovered codeigniter framework, and I knew right a way that this is it! Everything just clicked together when I saw how the framework organized in oop style.

  • unknown

    Absolutely marvelous.

    The create account does not verify someone with those credentials has already signed up. So, someone could sign up with the same credentials multiple times / use same E-mail address, etc…

  • http://www.bloghispano.com.ar Alfredo

    I say, TKS!, is a nice tutorial, i am intruduce in CI.

    The problem that i have now is that i dont find in anywhere “Password Recovery”…this is usefull if any lost the password, send this by email.

    Any add this issue?

  • Loco

    Impossible for me to download @ bilp.tv
    I just get 99% and then the Download fails.

    Can you plz upload this resource to a second hoster.

  • http://team2648.com Blake

    Best tutorial YET!

    Well done.

    Don’t worry about being boring.

    I was wondering where that neat css editor thingy that you were using to edit css and see page at the same time.

    Well I am assuming its a FF plugin. Would you share the name?

    Thanks,
    BB

  • http://sm11963.info Sam

    Second on Blake’s comment. What was that plugin/addon that he you used to edit the css?

  • Sam

    I got it

    Web Developer Tools