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.



I am getting the “You are NOT authorized’ message again and again. Any help?
This is what is in my Login class:
function validate_credentials()
{
$this->load->model(‘membership_model’);
$query = $this->membership_model->validate();
if($query) // if the user’s credentials are validated
{
$data = array(
‘username’ => $this->input->post(‘username’),
‘is_logged_in’ => true
);
$this->session->set_userdata($data);
redirect(‘chat/index’);
}
else
{
$this->index();
}
}
This is the similar to the “Site” class in the TUT.
class Chat extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->is_logged_in();
}
public function index()
{
$data['main_content'] = ‘chat_view’;
$data['user_id'] = $this->session->userdata(‘username’);
$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)
{
echo ‘You don\’t have permission to access this page. Login‘;
die();
$this->load->view(‘login_form’);
}
}
}
If you are testing on localhost, go to config and see if this settings work for you
$config['sess_cookie_name'] = ‘cisession’;
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = ‘ci_sessions’;
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['cookie_prefix'] = ”;
$config['cookie_domain'] = ”;
$config['cookie_path'] = ‘/’;
$config['cookie_secure'] = FALSE;
Be sure to clear cache and empty the ci_session table from the db.
I got error when using mysql_num_rows is it deprecated? I could not logged in the account i use this code to my class mebership_model
function validate(){
$condition = FALSE;
$this->db->where(‘username’, $this->input->post(‘username’));
$this->db->where(‘password’, md5($this->input->post(‘password’)));
$query = $this->db->get(‘login’);
if($query->num_rows == 1){
$condition = TRUE;
}
return $condition;
}
please hel[ >:(..,
Hi! thank you very much for your tutorials! It is really helping me a lot, we have a CI project (given today) due after two days, and because i have no background in php and CI, I was sure that I won’t be able to do it. But, your videos gave me hope! I understand CI better now, thank you again!
I just have a few questions: (I hope you don’t mind!)
1) how would I check if the user is an admin? In my database, I have a field named Is_admin which has the value 1 if the user is an admin, a link in the home page will be enabled/disabledd, if not it is not visible/enabled…
2) How can I display an message prompt whenever the user enters invalid/empty information?
again thank you very much for your superb tutorials and your help :)
Dear jeff..
according to your tutorial day 6 login , in my controller , it is not redirecting me to site/members_area it only redirect to the validate_credentials ….
please i need help as i am stuck over this..
Thanks for sharing these great tutorials Jeffrey.
My styles (styles.css) do not get applied when I click the Create Account button.
They work fine on the Login form, but not on the Sign Up form.
Now, what thing could cause that to happen? I followed the tutorial step by step, so I really don’t get HOW this screws up!? The styles are added in the header, and it’s the exact same header I’m using all the time. This has to be a bug!?
Anyone have any ideas?
Try referencing your styles via the whole URL and not just relative.
I’m guessing you’re doing something like ‘assets/css/styles.css’, try ‘http://domain/assets/css/styles.css’
I had this issue recently.
Hi, i just couldnt find this in the documentation: $this->db->where(). Can somebody explain this to me pls?
Why didn’t you go over a logout function? I know it was a big tutorial to begin with but that’s the other half of the puzzle.
Great tutorial, just what I was looking for. Thank you!
i noticed you did $query = $this->something in the IF statement… won’t that IF always be true becuase it’s just returning a value? wouldn’t it make more sense to just do if($this->something). i don’t know if i’m wrong or you just missed it.
sorry. this is in regards to the member creation process. the query I’m referring to is when you call the model to create it.
THANKS!!!!!! Very Helpful
I know this tutorial has been around for awhile but you can also do;
$this->session->sess_destroy();
redirect(‘some/page’);
Thanks for the tutorial, would like to see more!
These tutorials have really helped me gain a better understanding of MVC! Thanks!
For those having the problem with the login validation, change :
$query->num_rows == 1
to
$query->num_rows() == 1
Actually what I posted above doesn’t make a difference. It turns out that I had multiple records in the database with the same username and password. Since we are checking for $query->num_rows() == 1, the conditional statement was never executed.
i can’t get the css files right. could you explain how the css files are called?
“Unable to load the requested file: stylesheet.css”
exactly on loading the basepath
i am using the latest version, so there are some differences to your version here.
This was an excellent tutorial, btw.
hi again!
Forget about my previous problem, i had to modify sth, thanks the best tutorial! :)
Hi everyone, I’ve just complete the tutorial but here I have some weird thing happening. When I try to access the members area without the $is_logged_in set, the system redirects to the login screen, just like I expected, but it also outputs the member page contents after the login page content… Does anyone have any idea to solve this? I´m using the last version available on this date.
Here is the SITE controller:
is_logged_in();
}
public function restrito()
{
$this->load->view(‘site/site_main’);
}
public 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'] = “inicial”;
$this->load->view(‘includes/template’, $data);
}
}
}
i need to save the date of last logged in of each client , i thought about adding a column (‘last_access’, date) in clients table , any better idea ?
That is easy to do, and you don’t need CI to do it. Just add the field in PHP MyAdmin and then set it to automatically update each time the record is written.
You should add a screen shot or CREATE script of your MySQL database so that we could reproduce it for testing/dev purposes without having to guess on its structure.
Great tut!
The md5 function is not working for me in the site model. Every time i include it as
$this->db->where(‘password’, md5($this->input->post(‘password’)));
my form just loads the else clause in the validate_credentials function. When i take it out and insert a ‘naked’ password in to my database to test, i get the proper redirection to the members area. This has got me stuck for hours on end. What could be the problem why is the md5 function causing problems.
function is_logged_in(){
$is_logged_in = $this->session->userdata(‘is_logged_in’);
if(!isset($is_logged_in) || $is_logged_in != true){
redirect(‘login’);
}
}
doesnt work with load view, I use redirect.
The logic is that you load views and models into your controllers.
If you followed the tutotial, both “site.php” and “login.php” in your case are controllers, in the “controllers” folder.
So I presume what you did is tryied to load the controller “login” into the controller “site” refferencing “login” as a view:
$this->load->view(‘login’);
wich doesn’t exist.
Best regards ;) !
Amazing tutorial. Its very hard to follow, especially because I am a newbie in the OOP stuff. But really, you have made a great job with this tutorial.
I understood why Frameworks and OOP is the way to go with scripting.
Many many thanks mate.
Amazing FIVESTAR+ tutorial Jeffrey !
I’m new to CodeIgniter and this video was one of the first I’ve seen on making my very first basic aknowledgments on this great framework. Thank you, It helped me a lot to get the mechanism !
I’ll also report an issue:
You forgot to make a check wether the inputed ‘username’ is already in the database before inserting new data…
For as far as I’ve arrived, I believe that’s simply done by adding the ‘is_unique[table.field]‘ rule to the ‘set_rules’ method from the ‘form_validation’ class called on the ‘username’ input field !?
$this->form_validation->set_rules(‘username’, ‘Usernmae’, ‘trim|required|min_length[4]|is_unique[membership.username]‘);
Best regards!
I presume my last post was cancelled by “moderation” due to the fact that the spotted issue has already been “spoted” and solved by other users in the previous posts… my bad, didn’t checked.
But I still wan’t to thanks a lot fot the videotutorial that has been so illuminating concerning CodeIgniter, since that part of the post got lost too…
FIVESTAR Videotutorial Jeffrey! Many thanks! You rock!
Great tutorial! Thank you very much. I would love to see how to include Facebook and Twitter login to this. I haven’t seen any tutorials on that.
In case some of you are using Bitnami local to work on this, there is a bit of a trick to get the css working…
Move the CSS folder to frameworks/codeigniter/htdocs
Now the code for base_url should work.
<link rel="stylesheet" href="css/style.css”>
Another friendly helper, the construct in this video is different from the 2.x version most people are running.
class Site extends CI_Controller {
function __construct() {
parent::__construct();
$this->is_logged_in();
}
Hope that helps some of you who were as stuck as I was :-P
Sure did, thanks!
The links for this tutorial seem to be bad or missing. Can anyone point me in the right direction?
Another great tutorial.. Loving your series. Now, I am understanding Codeigniter and PHP in better sense..
Thanks a ton Jeffrey :)
The video link is broken. Please fix it.
Thank you.