Step 3.1 – Creating the login and logout page with Ion Auth

Auth.php which we moved inside controllers, is an example controller, so we can pretty much take whatever we need from there and use it where we need it.

As you can see, the index() method first verifies if the user is logged in by using the method $this->ion_auth->logged_in() .

So, if we need to verify this on our admin area why not move the method inside the constructor of the Admin_Controller?

Now, you may ask, where did we load the session? We didn’t. We left that one to the Ion_Auth library.

OK. As you can see, in the constructor we first verified that the user is logged in. If is not, we redirect to the login() method of the User controller.

So, let’s create a User.php file inside application/controllers/admin and create a login()  and a logout() method inside it:

As we won’t extend the Admin_Controller (we can’t because Admin_Controller’s constructor calls the ion_auth library, which is also called by the User controller…), we should load the ion_auth library inside the constructor of our controller to work with users.

In the login() method we first want to see if a form was submitted. If it was, then we try to see if the credentials are ok:

As we are going to create a form, we will load the form helper in the controller. Now, let’s create the form in the login_view.php inside application/views/admin directory:

It looks ok, but we shouldn’t see the menu unless we are logged in. So let’s go into our admin_master_header_view.php and make sure that the menu is only shown to the logged in users:

Now, if we visit http://localhost/admin we will be greeted by the login form.

Let’s return to our login() method and do the checks for those who fill the form and submit it:

Now, if we give the wrong credentials we should get returned to the login form.

Also, if we try to login with user: “” and password: “password” we should be greeted by the dashboard.

What about the logout?

Well… the logout is a simple call of Ion Auth’s logout() method. So let’s just work with our logout() method inside the User controller:

Now, we should put a Logout link on our horizontal menu, so let’s go to application/views/templates/_parts/admin_master_header_view.php and put the link in there:

Now, that looks great. Hope you enjoyed. Next we will use more of the Ion Auth library methods to administer the groups.

0 thoughts on “Step 3.1 – Creating the login and logout page with Ion Auth

    • Please don’t touch me. But if you want to get in touch with me, you can at any time write me at[at]gmail[dot]com

      • not abel to access this “http://localhost/admin” link generating error

        Object not found!

        The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

        If you think this is a server error, please contact the webmaster.
        Error 404
        Apache/2.4.7 (Unix) OpenSSL/1.0.1e PHP/5.5.6 mod_perl/2.0.8-dev Perl/v5.16.3

  • Hello,

    I got an error:

    The file/controller MY_Session_files_driver.php does not exist in application\core directory
    Why is that? Do I have to search for that file somewhere? Would you please help? Thanks in advance.

    • This must be related to using an older version of CodeIgniter, or the fact that you didn’t setup the session config data corectly. First of all make sure you have the latest version of CodeIgniter by downloading it from their site. After that, make sure you’ve setup the session correctly. 🙂

      • I am using the latest codeigniter version. I set and configure the session files as instructed, but it still showin that error message. I even delete and reset everything relate to the ion_auth as well.
        Back to the learn codeigniter in small steps: Step 9, is it maybe about the hook configuration? Because I don’t follow that step. Thankyou.

        • Now I remember. Yes, you are right. The problem is at the hook configuration. I’ve met this error before but I didn’t pay any attention to it because in the end I chose Jim Parry’s way of including the files. Could you try this in the App_Controllers.php and tell me if it solved your problem?

  • Social (twitter, facebook, g+) register and social login with ion auth will be a great tutorial if you create on!

    Thank You!

  • suon samoun says:

    I have followed all the step but I got this errors:
    Error Number: 1146

    Table ‘ci_admin.ci_sessions’ doesn’t exist

    SELECT data FROM ci_sessions WHERE id = ‘bcbdffa6fd55bc5db0c215c8ee41b5905b895db9’

    Filename: libraries/Session/drivers/Session_database_driver.php

    Line Number: 156
    Can you please tell me why?

  • Me too…I vote for a tutorial about Social (twitter, facebook, g+) register and social login with ion auth. It will be a great addition! Thanks

  • Great tutorial, helped me a lot to understand ION Auth… I am trying to learn ION Auth to use in my codeigniter project, how can i create registration or sign up page using ION Auth..

    • Hello, the library on Github already has an example controller that could help you get started, but if you already are comfortable with CI you could easily create the controller and the views. Maybe this is a good moment to create a tutorial about this subject 🙂

  • Hi.
    I would like to thank you for the tutorials !!
    Very detailed and easy to understand.
    I don’t have issues yet but on login it doesn’t use bootstrap is there a reason for that?

    • Hello. As you can probably figure out, the login view is not part of the administration area, as anyone can access that part. That is why I thought it would be better not to use an administration area specific CSS stylesheet 🙂

  • Hello avenirer,

    I have been reading your tutorials but I have had a little problem completing this one, When I try to access localhost/admin the page does not load. The loading circle on my chrome tab just keeps spinning.

    So far I have been able to narrow it down to a problem loading the ion_auth library. As soon as I add $this->load->library(‘ion_auth’); the page won’t load. I followed the tutorials closely and even tried copy/pasting when I couldn’t get it to work.


    • Did you make sure you’ve set up the sessions correctly? Could you send me your application and datatabase in a .zip at Also, make sure that the controller that has the login() method is extending MY_Controller and not Admin_Controller

  • Hi .
    I have a problem in login form.
    The problem is after verifying the username and password , if the user password is incorrect and shows no error message, but if you try again to enter the correct data dashboard and displays the above error.

  • Hello Sir,

    I got a problem, i have followed steps (not yet all) after this sentences of your tutorial “Now, if we visit http://localhost/admin we will be greeted by the login form.”

    I pretty confident have followed all your instruction, but really cannot figure out why the problem appears here.

    Here is my error message:

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: MY_Loader::$ion_auth

    Filename: _parts/admin_master_header_view.php

    Line Number: 14

    The line number 14 mentioned above in my code is:

    Looking forward to hear feedback from you Sir

  • Thank you very much Sir,

    I do following your 1-6 steps but skipping the step 8 because it is written ‘Optional’, i think that is my mistake LOL.
    but now I completed all instruction on step 8 and no more problem with session.

    The problem still exists until i add a new parameter on Autoload.php
    $autoload[‘libraries’] = array(‘session’,’ion_auth’);

    And the problem now is disappeared.

    Sir, you are awesome. My respect to you Sir.

  • I just wanna let you know Sir,
    My stupid mistake is by creating a new php file called Admin_Controller.php inside controller/admin folder instead of modify the content of Admin_Controller class inside MY_Controller.php. I apologize of my stupidity sir LOL.
    Probably you shoud make a note about it on the admin_controller section above sir, to avoid other stupid people asking stupid question as i did LOL. And a little note about using sessions with database.
    no additional parameter required to add on the autoload libraries like what i mistakenly did before.

  • Hello
    Very nice tuorial really easy to follow

    I have a problem on when i try to access the admin page it says

    Not Found
    The requested URL /admin was not found on this server.

    I’m working with wamp and all the configuration was done on that side for my project but
    so i can access it localhos/project and directly project can’t find why i don’t access the admin part

    Thank you

      • Thank you for the info

        Now that i try to access my admin page it gives me this error

        A Database Error Occurred
        Error Number: 1064
        You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE id = ‘55152bb2ca8ba53de851e072436b317835dce80e” at line 2

        SELECT data WHERE id = ‘55152bb2ca8ba53de851e072436b317835dce80e’
        Filename: libraries/Session/drivers/Session_database_driver.php
        Line Number: 160

        Just can’t find where
        thank you

          • Having almost same issues, but in my case, I see that the ‘identity’ field is not being built within the query.
            Tried to change manually in the models/Ion_auth_model.php file, but it does the same error, with ‘identity’ built in the query, and does not log on.
            What should I do? I’ve even switched the old model.php file for a fresh one to see if the issue was in it.

            Error Number: 1064

            You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE = ‘administrator’ ORDER BY id DESC LIMIT 1′ at line 2

            SELECT email, id, password, active, last_login WHERE = ‘administrator’ ORDER BY id DESC LIMIT 1

            Filename: models/Ion_auth_model.php

            Line Number: 973

          • Make sure you’ve set up the configuration of ion auth, corect. I am reffering here on setting the identity field. From your error I understand you have “email” set as identity…

  • Sir,
    i have a request, would you please adding tutorial about creating register page for new user?
    because sometimes we need to let a new user to make a registration process, not created by admin. A verification via email should be fantastic.
    There is no a very clear tutorials about this in other website

  • Hello Sir,
    Sorry for spamming your website,

    Just wanna let you know that (and maybe other user who is seeking the same thing as i did), i already successfully created a Register page.
    How it works is very similar to function create() inside controllers/admin/Users.php, at the end of the function, it calls ION AUTH register() function.

  • Thank you for this tutorial.
    after following the step the login display but if i login its will refresh and display 404 error .
    Please am newbie to codeigniter i need your help

  • I finished this step: thanks for your tutorial…
    Just a note: with ‘refresh’ it does not work: it returns a white (empty) page.
    Without this parameter, it’s works well.
    I don’t know why. but not very important cause it work.

    • I do not understand. What do you mean when you say “is not working for post requests”? Ion Auth has nothing to do with post requests, you pass it the values from controllers.

  • is there a way to remove the /user/ from the login process? So essentially it would be localhost/login rather than localhost/user/login…You have published some great tutorials on this site and I would also like to take the time to thank you for that!

    • Of course. You can open application/config/routes.php (or maybe you’ve put routes in an environment directory) and create a route

      $route[‘login’] = ‘user/login’;

  • Hi Avenir,

    Im learning & following your tutorial until this stage.
    But, i have an issue here. after submit a log in it always back to login form.
    is there any clue about this ?

    thanks. 🙂

  • Hi, guys!
    I fixed that “Error Number: 1064” issue, it was simpler than usually these things can be!
    I got some free time yesterday to check things out, and the code was perfect, both in my App and in the tutorial clone…
    So out of options, I’ve decided to look into an obvious hint: “Mysql error[..]”. Then that little cog began to turn inside my head: collation and the sorts in the database!
    Since my server has default lang as pt_BR, it uses latin-1 as collations. I’ve dumped the database .sql script, dropped it, changed to utf8 and utf8_something_ci it’s collation…
    Now it’s working like a charm!
    Just a little reminder that the error can be into small details, and it will sure bug you!

    Great tutorial, BTW!

  • Hi Avenir,

    I keep getting an error

    ” The configuration file ion_auth.php does not exist.”

    Checked the sessions, changed the ion_auth , checked hooks and unused them also but not changes ..
    Any pointers please?

    Thanks alot

  • Hello Avenirer,

    thanks for this tutorial !
    Sorry if someone already asked this question…
    If I well understand, your user.php controller with login and logout classes can only work if you have only one page to display (admin page).
    My concerne is that I have multiple pages which require an authentication. How can I handle that with your authentication method ?
    thank you very much !

      • hello and thanks for your quick reply !
        I’m not sur to understand your answer :-)…
        the problem is that on your login() function you perform a redirect(‘admin’, ‘refresh’);
        The problem I have is that “admin” is one of my multiple pages I have. Do I have to create a “user.php” page for each other pages where I need a authentication ?
        Hope I’m understandable 😉

        • Oh… you are referring to the redirect… OK… Let’s suppose a member (a user which is inside the “members” group) logged in. Also another user which is part of the “special” group logged in. You want to redirect them depending on the group they are part of… You simply do an if/else block:

          Does it make sense?

          • the pages a user will be redirected to doesn’t depend on the group it belongs to.
            Let say I have 4 html pages. Page1 and Page2 requiere an authentication, but not Page3 and Page4.
            How can I redirect to Page1 or Page2 when an user authenticates ? May be I have to record the page name he tried to access in a session variable and use it to redirect ?

          • Yes, you do have to save that inside a session variable. Inside a Page1 and Page2 you verify if the user is member of that group. If it’s not, you save two session variables: one that represents the url and one that represents the group name that the user must be part of in order to access the url. After that you redirect the user to the unique login page. If the user logs in and is part of the group saved inside the session, you redirect him/her to the url that is also saved inside the session variable. If he is not part of that group you simply redirect him to a default page (maybe with a message that he is not part of the group needed in order to access that specific url).

  • Ok thank you. This is what I wanted to do but unfortunately I still have a problem with codeigntier session.
    in my page1 controller __contruct function I assign “page1” to $_SESSION[‘sourcePage’] to record the source page.
    The authentication procedure works fine but redirect to home page. I do a isset test on the $_SESSION[‘sourcePage’] variable. If it’s empt I redirect to the homepage.
    Even if I correctly fill this session variable, it seems to be lost in the login controller function.
    I search on internet and it seems that tere’s a lot of troubles with session variables with codeigniter. Are you aware about that ? Any advise ?

    • I don’t know any “lot of troubles” with session variables within CodeIgniter. Usually the problems appear because people do not configure the sessions correctly. Could you give me a link with people complaining about these “troubles”? Also if you still have problems we can chat on hangouts. My address is

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

No spam? * Time limit is exhausted. Please reload CAPTCHA.