Auth library for CodeIgniter tutorial.
Right, on to the actual library:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Auth {
var $CI = null;
function Auth()
{
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->CI->load->database();
$this->CI->load->helper('url');
}
function process_login($login = NULL)
{
}
}
// End of library class
// Location: system/application/libraries/Auth.php
Save that to your application/libraries folder. Now our library is loaded in our controller and the error should be gone.
Back to the Auth library. As you can see, I’ve allready loaded an additional library, a helper and initiated the database connection in our construct method. I’ve also added the process_login method. As you’ll have guessed, this will process our login data from the form. I’m just going to copy paste the code for it. It’s so basic, I feel there’s no real need explaining it bit by bit.
Note: because we have to get some information from the database, you’ll offcourse have to change the database config file, don’t forget that.
function process_login($login = NULL)
{
// A few safety checks
// Our array has to be set
if(!isset($login))
return FALSE;
//Our array has to have 2 values
//No more, no less!
if(count($login) != 2)
return FALSE;
$username = $login[0];
$password = $login[1];
// Query time
$this->CI->db->where('username', $username);
$this->CI->db->where('password', $password);
$query = $this->CI->db->get('users');
if ($query->num_rows() == 1)
{
// Our user exists, set session.
$this->CI->session->set_userdata('logged_user', $username);
return TRUE;
}
else
{
// No existing user.
return FALSE;
}
}
As you can see, our process_login function sets a session variable and returns a true if the user was found with a matching password. What does our controller do when it receives a true? It uses a second function from our library: redirect. We’ll get to that in a bit.
First, a warning! As you can see, the passwords are stored directly in the database. They are NOT hashed. This is a huge security risk if your database would ever get lost/stolen. You should always, but always, hash your passwords. A simple sha1 or md5 hash is often good enough for small, simple sites. If you want more safety, look into the CI Encryption library and/or google “salts”.
Let’s add the redirect method to our library, it will handle the redirect from our login form to a page. For starters, let’s just let it redirect to the index page. We’ll make it a little more advanced later on in the tutorial.
function redirect()
{
redirect('/admin');
}







Bramme.net said
on Jul 30th, 2:04 pm |
[...] contact Bramme.net « Auth library for CodeIgniter tutorial. [...]
ahnShev said
on Sep 2nd, 5:45 pm |
It’ll throw an error for now because the library isn’t created yet, but we’ll do that on the next page.
Where is the ‘next page’?
Bram said
on Sep 3rd, 7:36 am |
My bad, there’s no next page link. I’ll fix it as soon as possible! I’m at work right now and don’t have access to my editor.
ahnShev said
on Sep 6th, 2:13 pm |
Thanx Bram
Erik Reagan said
on Sep 9th, 1:25 pm |
Thanks for the generous walkthrough and code. It was very beneficial to me and practically the last piece of the puzzle to a couple of projects.
saijin said
on Sep 24th, 4:21 am |
It works like a charm, thank you very, very much..
dcunited said
on Sep 25th, 1:23 pm |
A couple of security related notes:
1) Sticking the username and password in a cookie is a bad idea, I know you did not suggest it but you mentioned it and it is a major ‘no-no’. Use builtin session storage or create your own session id and send it in a cookie but please don’t put the username and password in the cookie.
2) Hashing the password is a must for security, I am glad you mentioned it. It also protects against SQL Injection robbing users passwords (SELECT username, password from users). I would highly recommend it.
Thanks for the tutorial, I am moving a site to CI and this gives me some insight into how others are creating auth within CI.
Tiago C said
on Sep 27th, 12:15 pm |
Thank you very much for the tutorial. It was a great help in developing a site I’m working on.
Although I would like to see other features implemented like user groups, restrictions, etc… Are you planing to write this tuts…?
Once again, thank you!
techdubb said
on Oct 13th, 9:52 pm |
excellent tutorial. thank you very much…
i did run into an issue however with the syntax of naming the constructor ‘__construct’ rather than the name of the class ‘Auth’. though you have it done correctly in the tutorial, the files you have for download still have ‘__construct’.
thanks again!
Ivar said
on Nov 3rd, 12:02 pm |
techdubb: That is a conflict between PHP4 and 5, the “__construct” syntax is explicitly version 5, so I expect you have 4 running on your end?
Php Cookie Redirect said
on Nov 18th, 5:47 pm |
Good site I “Stumbledupon” it today and gave it a stumble for you.. looking forward to seeing what else you have..later
kiruban said
on Nov 21st, 8:16 pm |
keep it up man! great work!
fourcs said
on Dec 5th, 3:23 am |
Any idea what could be causing me to get the error “cannot redeclare class Auth on line 3 of Auth.php” ? I haven’t altered your files at all. Thanks
Bram said
on Dec 6th, 10:38 am |
any chance you’re loading the library twice? like autoloading it and then also loading in your controller?
Could also happen if you have a model or other library called auth
Dimitar said
on Dec 19th, 3:56 pm |
Fatal error: Call to a member function on a non-object in c:\web\arsite\cms\system\application\libraries\Auth.php on line 114
this is the error that am getting when I go index.php/admin/
Dimitar said
on Dec 19th, 3:57 pm |
can you help me for the error
Bram said
on Dec 20th, 12:16 am |
I suggest you post more code over at the CodeIgniter forums. With just the error message I’m nothing.
Kristofefr said
on Dec 21st, 3:26 pm |
It works like a charm, thank you!
Although, i was wondering if it is possible to add something like:
If (logged_in) {
echo “logout link”
}
in the view file, so that i can check if the user is logged in and display links that only a logged in user i supposed to see…
Thanks again!
Bram said
on Dec 21st, 3:39 pm |
That is perfectly possible! You can use the $this->auth->logged_in() function for that. It returns TRUE or FALSE.
Annie said
on Jan 1st, 1:34 pm |
Cannot modify header information – headers already sent
Filename: libraries/Session.php
error occuring while using session ,
pls clarify
Bram said
on Jan 2nd, 12:03 am |
This is problem has nothing to do with the Auth lib. It is caused by output before you set sessions. Commonly, this can be caused by echo’ing variables from your controller, whitespace or linebreaks before your starting
I suggest you check all your controllers/models/libraries/helpers for any output (or whitespace). If the problem persists, it might be a good idea to write a post on the CodeIgniter forums.
Annie said
on Jan 2nd, 6:06 am |
thank u for reply, it caused because of whitespaces,i hav cleared it
Annie said
on Jan 2nd, 6:12 am |
$this->CI->session->userdata(‘redirected_from’), what we have to specify instead of redirect_from in the function redirect,did we have to define the location in the session.php in the library or is it is an inbuilt one in codeIgniter.
pls reply
Bram said
on Jan 2nd, 10:36 am |
You do not have to replace it, nor is it inbuilt by CodeIgniter: it’s taken care of by the Auth library: you’ll see the variable ‘redirected_from’ being set in the “restrict” function.
jinnn said
on Jan 7th, 6:30 pm |
is it suppose to be like this?
if(!isset($login))
{
return FALSE;
}
if(count($login) != 2)
{
return FALSE;
}
else
{
$username = $login[0];
$password = $login[1];
}
Ryan Yockey said
on Feb 14th, 4:19 pm |
Thanks for the tutorial. Everything worked perfectly.
batman said
on Mar 12th, 10:41 pm |
this is exactly what i’ve been looking for – many thanks!!!
something lightweight enough for me to get going, without all of the bloat of freak, redux, or auth…
txs
lc said
on Mar 24th, 1:25 am |
Thank you for the tutorial working fine but with FF, Safari and Chrome are working fine but not with IE(v.7) (I didn’t check with IE6)
How can I fix it?
Bram said
on Mar 24th, 7:31 am |
CodeIgniter works on the serverside, not client side. Which browser you’re using shouldn’t affect the system. Unless IE7 is bugging out on something in the session library. What version of CI are you using?
lc said
on Mar 24th, 9:05 am |
I’m using latest version of CI 1.7.1.
Is this issue something to do with godday server? I had a difficult time setting CI with their server.
It seems like something wrong with session. After logout, I can still access to portfolio page(news page works as expected). Also after login, I can still go back login page. This issue is only reproducible with IE7
Bram said
on Mar 24th, 9:08 am |
Hmmm, I’m not sure. I’ve heard problems before with godaddy concerning .htaccess files. You might wanna ask around on the CI forums. Maybe somebody could help there.
Also note: the session library has changed since I wrote this tutorial. I’ve been meaning to update it or write a new one, but I just didn’t get to it yet.
lc said
on Mar 24th, 10:10 pm |
After checked CI forums, I found out that many people has IE7 session issue but none of comment solve my issue
However, I change 2 lines of Auth.php and now working as expected
(tested: IE6, IE7, FF, Chrome, safari)
Auth.php
==================================================
/**
*
* This function redirects users after logging in
*
* @access public
* @return void
*/
function redirect() {
if ($this->CI->session->userdata(‘redirectedFrom’) == “”){
//if ($this->CI->session->userdata(‘redirectedFrom’) == FALSE){
…
==================================================
Auth.php
==================================================
/**
*
* Checks if a user is logged in
*
* @access public
* @return boolean
*/
function logged_in(){
if ($this->CI->session->userdata(‘loggedUser’) == “”){
//if ($this->CI->session->userdata(‘loggedUser’) == FALSE){
return FALSE;
…
==================================================
James said
on Mar 24th, 5:02 am |
You saved me loads of time… thanks a lot!
Raymond Selda said
on Apr 8th, 3:25 am |
Bram! Thank you so much for writing this tutorial! This is exactly what I need! I need to learn how to work out authentication in CI but I really avoided using auth frameworks because most of the times they’re really overwhelming and I really like writing code myself so I can better understand CI.
I already implemented your tutorial and I’m happy that it works! Keep up the good work and looking forward to your CI articles. Btw your English if fine!
Thank you Bram!
Tip: Try body { line-height:1.5em; } for better readability.
lekshmy said
on Apr 9th, 6:49 am |
A Database Error Occurred
Error Number: 1364
Field ‘user_data’ doesn’t have a default value
INSERT INTO `ci_sessions` (`session_id`, `ip_address`, `user_agent`, `last_activity`) VALUES (’17f14ae9124b9730ed16186540dd220e’, ’192.168.0.50′, ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;’, 1239254885)
please clarify this error
Bram said
on Apr 10th, 9:20 pm |
Dunno where it comes from… Is it possible that you’re using CI 1.7.x ? This tutorial was written for CI 1.6.x, with 1.7 the CI session library changed and things might not be compatible anymore.
Megges said
on Apr 15th, 10:15 am |
Wow, thats exactly what i was searching for! Thank you!
lekshmy said
on May 1st, 6:53 am |
A PHP Error was encountered
Severity: Notice
Message: fwrite() [function.fwrite]: send of 38 bytes failed with errno=32 Broken pipe
Filename: libraries/Email.php
Line Number: 1707
this error occured whhen i tried to mail some contents. can u pls clarify why its happening
Bram said
on May 1st, 9:14 am |
I don’t know what’s happening there, it seems like a problem with the Email library. Best to post your problem on the CI user forums I think.
CodeIgniter Authorization Systems said
on Jul 10th, 3:26 pm |
[...] Auth library for CodeIgniter tutorial For me personally I like this one the best. It is very simple and just enough to get started with out having tons of files to have to wade through. [...]
Em said
on Aug 1st, 1:40 pm |
That’s been very helpful. I hope to see more CI related tutorials from you.
ola said
on Aug 19th, 8:33 am |
thank you for this tutorial and i want to know what will be done if we specify user groups ??
ola said
on Aug 19th, 10:51 am |
Really i’m very passionate to know the part of user groups because the previous tutorial was very useful and so simple
Bram said
on Aug 19th, 12:12 pm |
Usergroups are currently not built in to the auth system. This is partly because I simply haven’t figured out myself how to effectively do it.
The logic behind it is: every page (or every function of your controller) has a unique ID. In a database (ideally, so you can manage it from a website) you store which usergroup has access to which id’s (or you store the opposite, which id’s they can’t access). In the restrict function of the auth library, you then need to do an additional check against the database if the user’s usergroup is allowed to that page.
Things get more complicated however when you need think of the dynamic navigation etc that will be needed: after all, you can’t have a user click a link, only to find out he’s not allowed on that page.
ola said
on Aug 19th, 4:10 pm |
thank you for your reply and hopefully continue to do that as you have a declarative way in your tutorial and i’m still waiting to be the first one read it, Good Luck
Felix said
on Apr 26th, 3:17 am |
hey Bram, awesome tutorial
one quick question, is there any possible way to autoload the auth->restrict function so you dont have to type it every time you create a function or page?
Thanks!
Bram said
on Apr 26th, 6:12 am |
You could do it with a pre_controller hook, I guess. I often use the function in my controller’s constructor, this makes that I only have to use it once per controller. I deliberately left it out though, since there could be cases where you wouldn’t need validation in one or two functions…
Regards
Felix said
on Apr 26th, 9:23 am |
hey bram, thanks for the quick reply.
I think it’s good idea to have it in the controller’s constructor too.
thanks for the great tutorial
Proiect finalizat « Klewos said
on Jun 23rd, 8:51 pm |
[...] I-am adăugat și o bibliotecă de autentificare și autorizare, în bună măsură bazată pe un excelent tutorial, însă îmbunătățită cu suport pentru roluri și utilizarea hash-urilor pentru manipularea [...]
Oxizequillime said
on Apr 1st, 9:03 am |
Никогда не слышала, заинтересовалась девушка. Где можно найти его книги?
Лави с помощью Лири отвела ее к кровати, раздела и уложила. Шатенка немного поворочалась и уснула. Выйдя из спальни, лавиэнка что-то нажала на стене, и дверь исчезла.
Попробуйте моченые корни валтака, посоветовала Барра и положила ей в тарелку какие-то мелко нарезанные белые клубни. Очень вкусно, хотя немного островато.
А что тут думать? удивилась Альмия. Я, вообще-то, жить хочу и не намерена умирать через два-три года. Да и магия вещь интересная. Для семьи тоже полезно. Ты сам подумай, как среагируют в обществе, когда узнают, что твоя дочь великий маг.
Это только малая часть войск чужаков, бросил напряженно о чем-то размышляющий фарсенский офицер.
[url=http://cotepdape.site11.com/article.php?article=128334]Калорий в день чтобы похудеть[/url]
[url=http://cotepdape.site11.com/article.php?article=320928]Грейпфрутовая диета[/url]
[url=http://cotepdape.site11.com/article.php?article=940918]Группа крови 2 положительная диета[/url]
[url=http://cotepdape.site11.com/article.php?article=416608]Лунная диета[/url]
[url=http://cotepdape.site11.com/article.php?article=942909]После гречневой диеты[/url]
[url=http://kettwicseoclud.vacau.com/article.php?article=834114]Диета долиной[/url]
[url=http://kettwicseoclud.vacau.com/article.php?article=110870]Ковальков как похудеть[/url]
[url=http://kettwicseoclud.vacau.com/article.php?article=496978]Поджелудочная железа диета[/url]
[url=http://kettwicseoclud.vacau.com/article.php?article=758110]Голливудская диета[/url]
[url=http://kettwicseoclud.vacau.com/article.php?article=901327]Диета при геморрое[/url]
[url=http://leuglasfizzto.vacau.com/article.php?article=975502]Похудеть за месяц 15 кг[/url]
[url=http://leuglasfizzto.vacau.com/article.php?article=297308]Кремлевская диета меню[/url]
[url=http://leuglasfizzto.vacau.com/article.php?article=510487]Похудеть не есть после шести[/url]
[url=http://leuglasfizzto.vacau.com/article.php?article=863145]Энерджи диет[/url]
[url=http://leuglasfizzto.vacau.com/article.php?article=841583]Похудеть на 2 кг[/url]
[url=http://noncmysqvides.vacau.com/article.php?article=441498]Похудеть здоровье малышева[/url]
[url=http://noncmysqvides.vacau.com/article.php?article=720396]Похудеть малышева[/url]
[url=http://noncmysqvides.vacau.com/article.php?article=577620]Игра похудей[/url]
[url=http://noncmysqvides.vacau.com/article.php?article=624332]Овощная диета[/url]
[url=http://noncmysqvides.vacau.com/article.php?article=910205]Как похудеть за неделю[/url]
[url=http://substertadi.vacau.com/article.php?article=39097]Диета на кашах[/url]
[url=http://substertadi.vacau.com/article.php?article=65617]Диета упражнения[/url]
[url=http://substertadi.vacau.com/category.php?category=19&page=2]Диета маргариты[/url]
[url=http://substertadi.vacau.com/article.php?article=195346]Тощая диета[/url]
[url=http://substertadi.vacau.com/article.php?article=425133]Диета для весов[/url]
[url=http://uscontuwi.comule.com/article.php?article=528196]Похудеть на 30 кг[/url]
[url=http://uscontuwi.comule.com/article.php?article=718007]Диета яичная неделя[/url]
[url=http://uscontuwi.comule.com/article.php?article=438615]Сахарный диабет 2 типа диета[/url]
[url=http://uscontuwi.comule.com/article.php?article=308960]Примерное меню диеты[/url]
[url=http://uscontuwi.comule.com/article.php?article=698803]Татьяна похудела[/url]
[url=http://winsnessvirlia.site11.com/article.php?article=854868]Диета 5 дней 5 кг[/url]
[url=http://winsnessvirlia.site11.com/article.php?article=929345]Диета[/url]
[url=http://winsnessvirlia.site11.com/article.php?article=255814]Диета андрея малахова[/url]
[url=http://winsnessvirlia.site11.com/article.php?article=206427]Похудеть с программой здоровье[/url]
[url=http://winsnessvirlia.site11.com/article.php?article=585735]Похудеть не есть после 6[/url]
hoosegent said
on Apr 9th, 4:17 am |
[url=http://veraser.if.ua]почта
[/url]
Immigration lawyer said
on May 5th, 5:46 pm |
I love the efforts you have put in this, regards for all the great blog posts.I have added your link to my blog here http://www.conveyancingquotes.info/?page_id=9 ,