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 1: Getting Started With the Framework
- Day 2: Database Selecting Methods
- Day 3: Sending Emails
- Day 4: Newsletter Signup
- Day 5: CRUD
Day 6: Sessions
More Viewing Options
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!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.



Very important: To avoid users from entering the admin area from the cache (by pressing the back button after logged out) need to add this 2 lines in the head tag of your views
Hi Yalon, what line is that? can you re-post it? I have a problem when i clicked the back button after I logged out I still can access the admin panel. Can you tell me how to fix it. Thanks in advance
Could you tell me what are those lines again? You could send me an email going to : mediasumo.com/contact.php . Thanks!
Is there any possibility that this video will be reuploaded? Because atm the link seems broken… Love the video’s hence why i ask :)
When I play the video here, in Firefox, it gets to the part where Jeff is talking about the database setup, and he’s entering a user into the database…then the video abruptly stops and starts over from the first.
Anyone else have this issue?
FYI, this only happens in Firefox, as I was able to view the whole thing in Safari just fine.
Just a follow up to this issue. Since I can play the whole thing with no problems in Safari, I have to assume that the problem was Firefox. I went ahead and shut down and rebooted my Mac, and tried again. This time, the video continued but there was a VERY annoying red block that flickered over 1/2 the page on the right hand side. So, this video continues to be unplayable in Firefox for me. Safari plays its with no incident.
I do have a few Firefox plugins that could be the culprit I suppose, but I’m not particularly interested in spending much more time with this. The other videos before this seemed to be just fine. But this one consistently has problems.
Hello,
I’m new to CodeIgniter.
In the tutorial, once you’ve logged in its says Welcome back, then your username.
How do you make it so it says Welcome back, then your first name and last name from the database?
Taa
Well you did a good job. I am new to switch from ordinary php programming to MVC architecture plus the codeigniter.
Now I am facing a little bit diffculty. I want to convert back end of website helpingstudent.com into MVC pattern it’s URL is http://www.helpingstudent.com/intranet
What I need to develop a template which have five sections i.e.
Header
Main menu
side menu
content area
footer
three area are dynamic i.e. Main menu, Side menu & content area
as you can view on http://www.helpingstudent.com/intranet.
Need you guidance how can I do that.
Thanks & regards
Sameer
@sameer
you can create a view file for each section and then load them sequentially in the controller like this:
function index() {
$this->load->view(‘header’);
$this->load->view(‘menu’);
$this->load->view(‘sidemenu’);
$this->load->view(‘content’);
$this->load->view(‘footert’);
}
you can read more about views in the user guide. hope that helps.
Great tutorial, however, what do you do about duplicate accounts. When a user creates an account with a same username, it then doesn’t let either user log in afterwards. Because there are two tables in the database with the same value.
There should be a rule that checks for a preexisting account.
Thanks
I had the same problem. I looked up making your own form validation rule. The example is exactly what your looking for.
http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks
To Check for Duplicate Username
Login.php (Controller)
$this->form_validation->set_rules(‘username’,'Username’,'trim|required|min_length[4]|callback_username_chk’);
function username_chk($username)
{
$this->form_validation->set_message(‘username_chk’,'Username already exist. Try different one.’);
$this->load->model(‘membership_model’);
if($this->membership_model->check_exist_username($username))
{
return false;
}
else
{
return true;
}
}
membership_model.php (Model)
function check_exist_username($username)
{
//$query_str = “SELECT username FROM membership WHERE username = ?”;
//$result = $this->db->query($query_str, $username);
$this->db->where(‘username’,$username);
$result = $this->db->get(‘membership’);
if ($result->num_rows() > 0)
{
//username exist
return true;
}
else
{
//username doesn’t exist
return false;
}
}
Its working fine for me…..
Thanks, that worked for me too :)
Nice tut, but why the hell are there no controls on the video to pause, rewind, forward?
Copy the link of the video in the vlc player and you are able to skip forwards, although the stream hasn’t finished loading.
Hi,
nice tutorial, but it doesn’t work for me. I coded it myself as you did step-by-step and when I try to login it always goes to the page ../login/validate_credentials which is blank.
I checked the code multiple times and found no mismatch with your tutorial. After downloading your sourcefiles and uploading to the webspace the same problem remains. Any ideas?
I got the same problem now, did you find a solution yet?
Hi, and congrats for this great tutorial series. Very useful in my opinion.
Following up to lesson 6, I managed to create a small login system version similar to the one explained, using sessions. In order to keep the user session stored in a database, I set everything in the config files to make it work, and it saves the data correctly. But I cannot ‘guess’ how to make the ‘remember me’ function to be working, no matter how much time has passed since the user last visited the site.
Does anyone tried to store sessions as well ?
Thanks a lot.
Can you upload the ci_series.sql database from this series as well? I already watched the tutorial and didn’t want to spend time watching it again. I jsut wanted to download the db to test it out. Thanks so much for making great tutorials!
I am interested in login. I am using wamp server. When i punch the url:
http://localhost/ci_day6/index.php/login/signup
it gives an error message like:
Deprecated: Assigning the return value of new by reference is deprecated in D:\PHP\wamp\www\ci_day6\system\codeigniter\Common.php on line 130
require_once( ‘D:\PHP\wamp\www\ci_day6\system\codeigniter\CodeIgniter.php’ )
Deprecated: Assigning the return value of new by reference is deprecated in D:\PHP\wamp\www\ci_day6\system\codeigniter\Common.php on line 136
A PHP Error was encountered
Severity: 8192
Message: Function set_magic_quotes_runtime() is deprecated
Filename: codeigniter/CodeIgniter.php
Line Number: 60
where is the database file…?
Hi Jeffrey. These are great and thorough.
I am using CI v 2.0.1 and am not totally up on OO concepts.
When I call the site controller __construct() method I receive the following error: Fatal error: Call to undefined method CI_Controller::Controller() in C:\wamp\www\ci_day6\application\controllers\site.php on line 6
class Site extends CI_Controller {
function __construct(){
parent::Controller();
$this->is_logged_in();
}
How can I adjust this code in the tutorial so that it works with the newer version of CI?
Thanks again!
Found the solution. Don’t know if it’s proper or not, but it does work.
Change:
parent::Controller()
To:
parent::__construct();
OMFG!!! THANK YOU!!! Been solving this problem for HOURS!!!!!
Hi, nice video
I’ve tried to copy some of the code to my own project – I have this:
class Projects extends CI_Controller{
function __construct(){
parent::__construct();
$this->is_logged_in();
}
function show(){
$data['main_content'] = “projects_view”;
$this->load->view(‘includes/template’, $data);
}
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'] = “login_form”;
$this->load->view(‘includes/template’, $data);
}
}
}
But when I’m not logged in, it shows me the login-form followed by the content of the “secret/secured” site I’m trying to enter (projects/show)
What am I doing wrong?
Thanks in advance
you have to include the die() call at the end of the view/content you are showing when user is not logged in, if not the content they are not supposed to see will be displayed below.
Hi again
I just tried to download the source and tested it (converted to CI2 though) – it is the same.
If I change:
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’);
}
}
to:
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’);
}
}
It’ll show the login_form followed by “This section represents the area that only logged in members can access.”
So either it is something in CI” or simply an error in this tutorial.
I also wondered why Jeff made the echo in the controller and out-commented the load-view part…
Well, I came up with this solution, if anyone should need it:
function is_logged_in(){
$is_logged_in = $this->session->userdata(‘is_logged_in’);
if(!isset($is_logged_in) || $is_logged_in != TRUE){
redirect(‘login’);
}
}
Hey guys, I’m a little confused at the moment because I’m getting this error :
An Error Was Encountered
In order to use the Session class you are required to set an encryption key in your config file.
So what do I do there? Secondly, I tried to add something there and it worked but . . . The who redirect didn’t work for me. Everytime i would click “login” it wouldn’t take me to ‘site/members_area’, it would refresh on ‘login/validate_credentials’.
I’m confused. :(
Sigh i figured out my problem. I was putting wrong password in. :|
what about the forgot password things… ?
i did it in it in simple php but i am not getting how to make it in the codeigniter..anyone help me?
i made one for me using this tuts:
http://girishrawate.pbworks.com/w/file/fetch/39352233/myOrkut_11.4.1.zip
Hi, I ran in to the following error message:
“Fatal error: Call to undefined method CI_Controller::Controller() in /Users/gero/Sites/my_proj/application/controllers/site.php on line 7
”
In one of the version changes this must have become impossible. I fixed it as following:
file: site.php
// before:
function __construct()
{
parent::Controller();
$this->is_logged_in();
}
// fix:
function __construct()
{
parent::__construct();
$this->is_logged_in();
}
in this blogpost I’ll submit other fixes too:
http://geronimo89.dk/2011/04/30/codeigniter-my-personal-ignition/
Thank you for your great screencast so far!
Was having a similar problem. Can you please tell what parent::__construct(); is doing and why we need to write it in the Site class?
I think we should test if is_logged_in also in login controller, so if the user is logged in we redirect him to members_area without displaying the login form
I am getting an error of
An Error Was Encountered
In order to use the Session class you are required to set an encryption key in your config file.
Does anyone know what that means or can any of you help me in any way? I’d really appreciate it, thanks.
Set a 32 alpha-numeric string (application/config/config.php)
/*
|————————————————————————–
| Encryption Key
|————————————————————————–
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = ’32charalphanumstring…’;
(obviously a little more sophisticated than whats above)
(tip – use a random generating alpha-num string generator)
Im sure there is lots more to know, so read up on (Setting your Key):
http://codeigniter.com/user_guide/libraries/encryption.html
I was getting this same error. After adding the key I am still getting another error even when the encrypted password is the same. Do you know what I am doing wrong?
Database screenshot (as you can see the password is the same):
http://i.imgur.com/pDaLm.png
Site error:
A Database Error Occurred
Error Number: 1054
Unknown column ‘”password’ in ‘where clause’
SELECT * FROM (`membership`) WHERE `username` = ‘test’ AND `”password` = ’098f6bcd4621d373cade4e832627b4f6′
Filename: /Applications/MAMP/htdocs/ci_6/models/membership_model.php
Line Number: 8
Pretty decent tuts so far (previous CRUD was a bit of a cop-out with hard coded U) – although my own main gripe is this damned infernal video player.
- If I reload or the page fails halfway through – needs to wait to re-buf – argh
- If press pause – silly pause/play blocking text
- And while I can live with it… the resolution is kind of poor
I know youtube has it down to a tee and so laves onet a little spoiled, but this player and the one or 2 others offered would make me think twice about perhaps not getting a paid account.
All in all – very helpful but with a few aggravations along the way – thanks all the same.
OK so I spoke too soon, this part 6 Login now at blip.tv is just horrible on my netbook.
Can’t zoom out and so I can only see about – at a guess – a half to a third of the screen.
Where can I find this video to watch or download?
Oops.. I found the link now.. :-)
This is a really terrific tutorial, and I appreciate all the hard work you must’ve put into pulling all this together. I’ve coded in years past, but nothing seriously for a long time, and never before with CI. I have a new Web application called Milepost that I’m putting together, and CI is going to be the framework. This definitely got me going in a strong direction, so thanks!
That said, I’m trying to include a link in my page navigation area that changes between LOGIN and LOGOUT based on whether or not the user is currently logged in.
So for example, in my login.php controller, I have the validate_credentials function that’s redirecting a successfully logged-in session to my main.php controller:
function validate_credentials()
…
$this->session->set_userdata($data);
redirect(‘main/home’); /* redirect logged in users to main controller */
…
}
So then in my main.php, I have the following:
is_logged_in();
}
function home()
{
$data['page_title'] = ‘Milepost – Main’;
$this->load->view(‘app_header’, $data);
$this->load->view(‘app_nav’);
$this->load->view(‘home_view’);
$this->load->view(‘app_footer’);
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata(‘is_logged_in’);
if (!isset($is_logged_in) || $is_logged_in != true)
{
redirect(login);
die();
}
}
}
The intent is to load the header, the nav, the home view, and the app footer. It loads all of them just fine. BUT…I have the following code in the app_nav.php view, which I thought would change the LOGIN link to either LOGIN or LOGOUT, but it doesn’t do so — it always displays LOGIN, never knowing the user is actually logged in already.
HOME |
session->userdata(‘is_logged_in’);
if (!isset($is_logged_in) || $is_logged_in != true)
{
echo “LOGOUT“;
//insert logout function here *******
}
else
{
echo “> LOGIN”;
}
?>
| PRODUCT TOUR | SUPPORT | ABOUT US
Can anyone point me in the right direction here?
@Dan,
You have your logic the wrong way around (in short you are asking CI to display ‘LOGOUT’ if the they are not logged in – remember !isset() checks if a variable is *NOT* set, hence the ‘!’ (not) logic operator). Swap the code around so it’s like this:
$is_logged_in = $this->session->userdata(‘is_logged_in’);
if (!isset($is_logged_in) || $is_logged_in != true)
{
echo “LOGIN“;
//insert login function here *******
}
else
{
echo “> LOGOUT”;
//insert logout function here *******
}
?>
Give that a whirl.
@ Dan:
Ich added a ‘logged_in_view’ or ‘logged_out_view’ view ro my template and set the view like this:
$data['main_content'] = ‘index_view’;
$data['navi_content'] = ‘navigation/logged_out_view’;
$this->load->view(‘includes/template’, $data);
whrer from i found tautorials for beginers?
I think there is some problem with loading this video, please check
Hi Jeff,
source dont work on php 5.3.5 :(
Thank you ! I love this tut.
here is the download link , right click -> save as :D
http://a44.video2.blip.tv/5870002834299/NETTUTS-CodeIgniterFromScratchDay6219.mp4
video can’t watch
Hi I am currently following the tutorial series and in this video when I get to 29:00 minute I cannot connect to the database I get an error
Database Error Occurred
Error Number: 1146
Table ‘login.membership’ doesn’t exist
SELECT * FROM (`membership`) WHERE `username` = ‘erick_barron’ AND `password` = ’07615022143da58699914f62de64301b65acd1b7′
Filename: C:\Wamp\apache2\htdocs\login\system\database\DB_driver.php
Line Number: 330
I replaced jeffrey’s name with mines, and I named my table membership, I don’t know why it says login.membership as a table. Also only other thing I changed was I used sha1 instead of md5
using codeigniter 2.0.2 and I don’t know if its the same in 1.7 but when I autoloaded the session library it told me to set a key and I dind’t see jeffrey do that.
Hello all,
I am having a bit of trouble displaying a “not authorized” message when someone tries to access a page without being logged in. When I try my code it ends up displaying the “not authorized” message, but it also shows the members only area. Here is what I have…
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_access_view’;
$this->load->view(‘includes/template’, $data);
//die();
}
}
If I remove the comment form the die(); nothing is displayed and my page source is blank…
It seems as though the function is dieing before it completes, but I don’t know any way to get this to work. Any help?
Thanks in advance,
Andrew
p.s. I am also trying to get the duplicate username checking function to work… maybe our gracious teacher would like do drop us a line on how to get that done? Just a thought…
I have the same problem too. I created a non-members view which gets displayed fine but is always followed by the members view. Commenting out the die() gives me a blank page too.
hi,
I am using same script as you showed on WAMP. codeigniter version: 2.0.3
The problem is that it is not working:
I got fatal error: Class ‘Controller’ not found on line 8.
I insert everything correctly… I already checked for writing mistakes – it just does not work.
How I can solve this??
Thanks.
in CI version 2.0 they added the prefix CI_ to the name of the classes.
So wherever Jeffery has:
class login extends Controller
change it to
class login extends CI_Controller
same for models.
Good tutorials, can you make a tutorial on creating admin-user level access using CI? thanks.
Really awesome job!! I’ve been using wordpress to develop for a long time but it is starting to fall short of my need and the forum moderators just keep suggesting plugins. Here’s a list of tutorials that would be great to add.
User management and roles capabilities
Gravity Forms functionality
Blogging
Creating Content Types
Looping through content types
Thanks!
Hey folks,
I am following the login script on my wamp server. When I get to testing the login form I get an error:
Not Found
The requested URL /ci/login/validate_credentials was not found on this server.
I have looked over my code and it mirrors the tutorial. Could someone please tell me what I may be doing wrong.
Thanks
Hi to all,
Anyone who can help me with my problem, I am new to CI and I followed this tutorial and it works great but I have noticed one problem during the implementation, when my session is destroyed after I clicked logout the session is properly destroyed but when I clicked back button of the browser it returns the previous pages. How can I solve it? Anyone who has the bright idea? Thanks.
-Jams
I really appreciate your tutorial online, great patients in explaining. You giving more information than any normal tutorial does, that so kind of you.
Please include the database table creation script too along with the source code files.
echo validation_errors(); gives a list of all errors for all text boxes together with i guess. I wanted each error to be appearing below each text box. So, I feel
echo form_error(‘username’);
echo form_error(‘email’);
would do the needful.
Can somebody help me? This small issue is not allowing me to continue this tutorial with success.
I was getting this error:
————-
An Error Was Encountered
In order to use the Session class you are required to set an encryption key in your config file.
———-
As suggested in this site. I added the encrytion key inside the config.php and then I got the following error with the password validation, but the password clearly is the same encrypted string.
——————–
A Database Error Occurred
Error Number: 1054
Unknown column ‘”password’ in ‘where clause’
SELECT * FROM (`membership1`) WHERE `username` = ‘test’ AND `”password` = ’45c571a156ddcef41351a713bcddee5ba7e95460′
Filename: /Applications/MAMP/htdocs/ci_6login/models/membership_model.php
Line Number: 16
—————————-
I even read the documentation and created an encrypted pass inside a variable using sha1. But still the same error. Check out this screenshot:
http://i.imgur.com/JwEZe.png
I will really appreciate if somebody help me figure this out.
it seems to be sql syntax error.
$this->db->where(‘”password’, $encryptpass);
it should be.
$this->db->where(‘password’, $encryptpass);
you added ” to the table name.
Silly me!. Thank you.
Hi everyone! can somebody upload a version that works on ci 2.0.3 ? I followed the course, and added the CI_ , but it still doesn’t work ( I get a blank page if I go to index) .
What were you using to edit CSS inline updating in browser?
“Wo0o Firefox update”.
That’s what made this tutorial brilliant!
here is a solution if you have multiple controllers that need to have a session check.
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
if(!$this->session->userdata(‘logged_in’) {
redirect(‘login_view’);
}
}
}
The next thing you can do is just extend the MY_Controller class!
class ControllerRequiresLogin extends MY_Controller {
function index() {
//call some views!
}
}
I hope I’ve helped some people with this handy trick ;-)!
Thank’s Jeff for your wonderful TUTS.
You introduced a template system in this TUT.
Normaly you have to submit data to the view. I have changed set the variable $link with the array for the view, Here an example:
$link = array(‘debug’ => “login successfull…”);
$data = array(
‘main_content’ => ‘debug_view’,
‘data’ => $link);
$this->load->view(‘templates/standard/includes/template’, $data);
.
Bye matze
http://blip.tv/nettuts/codeigniter-from-scratch-day-6-2973653 for the stream version.
This tut. is very old, I tried the source code and I got a lot of warnings telling me about some deprecated functions.