Вы находитесь на странице: 1из 13

Code Factory

Web Development for You Contact

Home Blog Simple Login with CodeIgniter in PHP

Simple Login with CodeIgniter in PHP


Posted on April 18, 2011 by Andres Arias 49 Comments

CodeIgniter is an open source Web Application framework built in PHP designed to make your life as a programmer easier, while allowing you good speed for development, and also good performance when the site is up and running. Being a Java developer for almost 10 years now, when I had to move to PHP I chose CodeIgniter for the following reasons: Easy to install and configure (being a newbie in PHP this was crucial) Clean and elegant MVC implementation Uses Active Record pattern for database access Overall small footprint and good performance Usually when you are building a program, the login/logout functionality is a must we always have to go through, so this quick tutorial will focus on this functionality, taking advantage of the benefits of using CodeIgniter instead of doing it from scratch in PHP.

Requirements
CodeIgniter framework. By the time this tutorial was done, the latest version was 2.0.2 Any Apache/PHP/MySQL stack. You can install the applications independently, or install one of those packages that have all of them bundled together.

Installing CodeIgniter
To install CodeIgniter, you only need to uncompress the Zip file you download from the site into your htdocs directory and youre good to go. Well configure the database access later.

Create the database


For this tutorial, you need a MySQL database with the following table:

1 CREATE TABLE `users` ( 2 `id` tinyint(4) NOT NULL AUTO_INCREMENT, 3 `username` varchar(10) NOT NULL, 4 `password` varchar(100) NOT NULL, 5 PRIMARY KEY (`id`) 6 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Remember also to add at least one user. Well add one user called bob with password supersecret.

1 insert into users (username, password) values ('bob', MD5('supersecret'));

Configure CodeIgniter
Database Access
Update the file application/config/database.php in your CodeIgniter installation with your database info:

44 45 46 47

$db['default']['hostname'] $db['default']['username'] $db['default']['password'] $db['default']['database']

= = = =

'localhost'; 'yourdbusername'; 'yourdbpassword'; 'yourdbname';


converted by Web2PDFConvert.com

Default Controller
We need to tell CodeIgniter to land into our login page instead of the default welcome page. Update the file application/config/routes.php in your CodeIgniter installation with you controllers name. Well call our landing controller login.

41 $route['default_controller'] = "login";

Default Libraries
In the file application/config/autoload.php you can configure the default libraries you want to load in all your controllers. For our case, well load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation

55 $autoload['libraries'] = array('database','session');

67 $autoload['helper'] = array('url');

Encryption Key
When you use the session library, you need to set the encryption_key in the file application/config/config.php.

227 $config['encryption_key'] = 'REALLY_LONG_NUMBER';

The Code
Here are the actual Views, Controllers and Model we are using for the login functionality.

User Model (application/models/user.php)


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?php Class User extends CI_Model { function login($username, $password) { $this -> db -> select('id, username, password'); $this -> db -> from('users'); $this -> db -> where('username', $username); $this -> db -> where('password', MD5($password)); $this -> db -> limit(1); $query = $this -> db -> get(); if($query -> num_rows() == 1) { return $query->result(); } else { return false; } } } ?>

Login Controller (application/controllers/login.php)


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Login extends CI_Controller { function __construct() { parent::__construct(); } function index() { $this->load->helper(array('form')); $this->load->view('login_view'); } } ?>
converted by Web2PDFConvert.com

Login View (application/views/login_view.php)


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>Simple Login with CodeIgniter</title> 5 </head> 6 <body> 7 <h1>Simple Login with CodeIgniter</h1> 8 <?php echo validation_errors(); ?> 9 <?php echo form_open('verifylogin'); ?> 10 <label for="username">Username:</label> 11 <input type="text" size="20" id="username" name="username"/> 12 <br/> 13 <label for="password">Password:</label> 14 <input type="password" size="20" id="passowrd" name="password"/> 15 <br/> 16 <input type="submit" value="Login"/> 17 </form> 18 </body> 19 </html>

VerifyLogin Controller (application/controllers/verifylogin.php)


This controller does the actual validation of the fields and checks the credentials against the database.

1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 2 3 class VerifyLogin extends CI_Controller { 4 5 function __construct() 6 { 7 parent::__construct(); 8 $this->load->model('user','',TRUE); 9 } 10 11 function index() 12 { 13 //This method will have the credentials validation 14 $this->load->library('form_validation'); 15 16 $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); 17 $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); 18 19 if($this->form_validation->run() == FALSE) 20 { 21 //Field validation failed. User redirected to login page 22 $this->load->view('login_view'); 23 } 24 else 25 { 26 //Go to private area 27 redirect('home', 'refresh'); 28 } 29 30 } 31 32 function check_database($password) 33 { 34 //Field validation succeeded. Validate against database 35 $username = $this->input->post('username'); 36 37 //query the database 38 $result = $this->user->login($username, $password); 39 40 if($result) 41 { 42 $sess_array = array(); 43 foreach($result as $row) 44 { 45 $sess_array = array( 46 'id' => $row->id, 47 'username' => $row->username 48 ); 49 $this->session->set_userdata('logged_in', $sess_array); 50 } 51 return TRUE; 52 } 53 else 54 { 55 $this->form_validation->set_message('check_database', 'Invalid username or password'); 56 return false; 57 } 58 }
converted by Web2PDFConvert.com

58 } 59 } 60 ?>

Home Controller (application/controllers/home.php)


This is the private page (only authenticated users can access it).

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); session_start(); //we need to call PHP's session object to access it through CI class Home extends CI_Controller { function __construct() { parent::__construct(); } function index() { if($this->session->userdata('logged_in')) { $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $this->load->view('home_view', $data); } else { //If no session, redirect to login page redirect('login', 'refresh'); } } function logout() { $this->session->unset_userdata('logged_in'); session_destroy(); redirect('home', 'refresh'); } } ?>

Home Page View (application/views/home_view.php)


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>Simple Login with CodeIgniter - Private Area</title> 5 </head> 6 <body> 7 <h1>Home</h1> 8 <h2>Welcome <?php echo $username; ?>!</h2> 9 <a href="home/logout">Logout</a> 10 </body> 11 </html>
The code is pretty easy to follow and understand. Also, you can download the code from here, so you can install it and test it in your location. Youll only need a full installation of CodeIgniter 2.0.2 and the table in your MySQL database. If you need any help, feel free to leave us a comment or shoot us an email. Also, this code uses a pretty basic form validation from CodeIgniter. If you need a more complex validation process, check CodeIgniters Form Validation docs at their site. Cheers!

Setting up Glassfish behind Apache


Posted in Blog, PHP

Custom Rules for JQuery Validation in Forms

49 comments on Simple Login with CodeIgniter in PHP


converted by Web2PDFConvert.com

govarthanan says:
January 11, 2013 at 7:52 am

its good one

Joe P. says:
January 13, 2013 at 11:16 pm

Nice and concise. Thanks

alex mbiru says:


January 14, 2013 at 2:08 am

this script help me a lot, keep the good work.

flashbag says:
January 15, 2013 at 7:30 am

I was just searching for simple login example. And Ive founded it! Thank you!

Eb says:
January 15, 2013 at 8:45 pm

thanks for the great tutorial. Im just getting started with code igniter. Just an observation, User Model (application/models/user/php) is supposed to be User Model (application/models/user.php). Wrong?

Andres Arias says:


January 15, 2013 at 9:48 pm

Fixed! Thanks for the heads up!

http://tinyurl.com/0577horn32250 says:
January 16, 2013 at 12:01 pm

Simple Login with CodeIgniter in PHP Code Factory was in fact a great posting. In case it possessed much more pics this would be even much better. Regards ,Gilda

Preetham says:
January 18, 2013 at 1:27 am

thanks a lot for posting this.

Tony says:
January 20, 2013 at 6:24 am

Thanks for this! It helped me a great deal. It was posted back in 2011 from the looks of it, but still works line for line with the current version in 2013.

converted by Web2PDFConvert.com

Shahzeb Babar says:


January 22, 2013 at 2:47 am

It is open for SQL injection. tried it myself.

kap says:
January 22, 2013 at 4:24 am

This is fantastic work.. and also thanks

kap says:
January 22, 2013 at 4:25 am

(dap)

SHWETA says:
January 22, 2013 at 5:07 am

i have tried with your code and created database and tables but not getting how to run this,please help me

Taukil Ali says:


January 24, 2013 at 5:46 am

Great post .I like it.

Andres Arias says:


January 24, 2013 at 8:51 am

Hey! Can you post the error you are getting? Or send me an email (aarias_at_codefactorycr.com)

julian says:
January 24, 2013 at 9:37 am

you already put the url helper in the autoload.php so why did you still load it in the login controller?

Andres Arias says:


January 24, 2013 at 9:54 am

Good catch! It is not required in the controller as you say. Ill fix the post. Thanks!

Austin says:
January 27, 2013 at 5:53 am

Im getting a 404 on verifylogin, yet I followed your guide to the teeth. Could it be an htaccess problem?

Andres Arias says:


January 27, 2013 at 4:28 pm

Good catch! I updated the code in user.php to use a more proper version of $this->db->where(), instead of concatenating strings. More
converted by Web2PDFConvert.com

info here: http://ellislab.com/codeigniter/user-guide/database/active_record.html

Andres Arias says:


January 27, 2013 at 4:29 pm

Hey Austin! Well, it could be an .htaccess problem, since by using form_open(verifylogin); in the tag, youre using CodeIgniters helper to create an absolute path for the form action, instead of building the url yourself. Have you tried this without the .htaccess to see how it goes?

andres says:
January 28, 2013 at 9:44 pm

hi, sorry for my english. how do I validate that a user is logged in, if I have multiple controllers. because when I click it back in my browser, and I logged out, I can see my application. Im trying to apply your example to my application but I could not get it right. Thank you.

Andres Arias says:


January 28, 2013 at 10:53 pm

In verifylogin.php (line 49) you add the user info to a key called logged_in in the session, so in the private pages you need to check that this logged_in key exists in the session, like this: if(!$this->session->userdata(logged_in)){ //Not logged in, redirect to a public page redirect(home, refresh); } And to log out you can do this: $this->session->unset_userdata(logged_in); Cheers

andres says:
January 28, 2013 at 11:11 pm

if it is exactly what Im doing pass your example to my application, but I have more drivers also I have to validate these and did what you commented: if (!$this->session->userdata(logged_in)) { redirect(home, refresh); } I log off, I get redirected to the login form, but when clicking back on my browser allows me to see all my application. : ( Curiously works fine in Internet Explorer but not in Firefox, Chrome and Opera. Do you speak Spanish?. Greetings from Cali, Colombia.

zul says:
January 28, 2013 at 11:28 pm

Why i get 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.

converted by Web2PDFConvert.com

I already follow your instruction. anybody can help me?

Jeff says:
January 29, 2013 at 1:12 am

Hi! I get this after following your tutorial: An Error Was Encountered Unable to load the requested class: database, session Can anyone help me? I was wondering what happened?

Manoj Damkondwar says:


January 29, 2013 at 1:55 am

Thanks man now I am starting with codeiniter its very useful for me..

Prashanth.Maddur says:
February 6, 2013 at 3:35 am

its good for beginners.

Morris says:
February 7, 2013 at 1:41 pm

Thanks!!! this really help me a lot

Christiaan Janssen says:


February 8, 2013 at 1:24 am

Awesome tutorial. Works like a charm!

peter says:
February 10, 2013 at 3:04 pm

Thank you very much, very useful. Ive got only one problem. I think it uses only 1 session for multiple users !? If i log in as for example bob and in a new tab mike, then when i have a shopping cart in the member area and want to shop, then i add something and go to the other tab where mike is logged in and put something into the shopping cart, the tab where mike is logged in changes to bob. thanks in advance

Andres Arias says:


February 10, 2013 at 9:23 pm

Hi Peter I think the problem youre having is in your browser. The same happens to me in Firefox and Chrome, since the session is shared among tabs (e.g. youre in amazon and open multiple tabs and add them to your cart, keeping the logged in session). You can try this with a different browser (two different browsers in the same machine) or maybe with Chrome in incognito mode, since its a separate window and process from the non-incognito window. Cheers

converted by Web2PDFConvert.com

Sebastian says:
February 11, 2013 at 6:43 am

After doing exactly as requested in the whole login tutorial, what url should I run in my localhost given my local root is localhost/simple_login? pliz help

Vladimir says:
February 11, 2013 at 7:14 am

I dont understand one row. This is in function check_database($password) $username = $this->input->post(username); Why you dont put too variable $password? fe. $password = $this->input->post(username); Thanks.

Vladimir says:
February 11, 2013 at 7:16 am

I made mistake. Sorry. I dont understand one row. This is in function check_database($password) $username = $this->input->post(username); Why you dont put too variable $password? fe. $password = $this->input->post(password); Thanks.

jithu.majinu says:
February 12, 2013 at 4:59 am

realy it is good tutorial for beginners thank you

pantas says:
February 12, 2013 at 8:20 pm

help me an error i try it on appserv 2.5.9, but i get this error.. Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, psinaga24@gmail.com and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log.
converted by Web2PDFConvert.com

Apache/2.2.4 (Win32) PHP/5.2.3 Server at localhost Port 80 please help me..

angel says:
February 13, 2013 at 7:12 am

thanks!

Andres Arias says:


February 13, 2013 at 7:21 am

Hi pantas Is there a way you could check Apaches logfiles? It seems something went really wrong and threw out that 500 error. You can check for the error_log or php_error_log (depending on the lamp server youre using). Cheers

Andres Arias says:


February 13, 2013 at 7:23 am

Hi Sebastian The url should be something like http://localhost/simple_login/index.php/login (or remove index.php if you have changed the config for this) Cheers

Andres Arias says:


February 13, 2013 at 7:24 am

Hi Vladimir As far as I understand, the form_validation methods accept only one field since theyre validating a field in a form. The $this->input>post(username) is a trick to have both params when checking the database. Cheers

Gopika says:
February 13, 2013 at 11:13 pm

Hi Andres Thank you for the tutorial. As a beginner with codeigniter, it was very helpful. I wanted to create this in both chinese and english. https://github.com/EllisLab/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n I had followed this steps and was able to create the language change. But then the login is not working, it is showing Call to a member function select() on a non-object. Any help will be appreciated. Thanks a lot.

converted by Web2PDFConvert.com

Bar says:
February 14, 2013 at 7:03 am

That was really useful. I am learning the codeigniter framework and i can say it is the best sample ive ever seen. Thank you.

funti says:
February 15, 2013 at 1:59 pm

once i have comment this line redirect(home, refresh); than it works without any error message. but after login it will lead to index.php/verifylogin is it fine ? and what to do to redirect it to another page !

aruna says:
February 16, 2013 at 6:32 am

Really good one . searching for simple sample application to learn codeigniter and found it here

Scavanza Laziendo says:


February 18, 2013 at 3:07 am

what is the action in the tag form in the login_view?? i dont get it,,because if you hit the submit button nothing will happen,,oh and by the way thanks for the tutorial i love it

Jack says:
February 18, 2013 at 9:58 am

Hi, Your tutorial was very helpful! However when I attempt to log in I get this error: The requested URL /LoginTut/login/VerifyLogin was not found on this server. Do you know what might be the problem? I posted a question of my problem on StackOverflow. It describes in detail what I did and the problem I am now having. http://stackoverflow.com/questions/14940118/simple-login-system-using-codeigniter-returning-404-on-login#comment20967412_14940118 Id appreciate any help on the topic but once again fantastic tutorial!

Nitish says:
February 19, 2013 at 4:25 am

Thanks for the tutorial. I am getting the error A PHP Error was encountered Severity: Notice Message: Undefined property: Verifylogin::$form_validation Filename: controllers/verifylogin.php

converted by Web2PDFConvert.com

Line Number: 18 line number 18 is $this->form_validation->set_rules(username,'Username,'trim|required|xss_clean);

Andres Arias says:


February 19, 2013 at 7:36 am

Hi Nitish Do you have the line $this->load->library(form_validation); before line 18? You need this line to load the validation library. Cheers

Andres Arias says:


February 19, 2013 at 7:38 am

Hi Scavanza The action in the form is added here => < ?php echo form_open('verifylogin'); ?> (login_view.php, line 9). This is the same as creating the full tag Thanks

1 Pings/Trackbacks for "Simple Login with CodeIgniter in PHP"

Simple Login using CodeIgniter & Database | imron02 says:


June 1, 2013 at 9:15 am

[...] Very easy if you understand this. Full Code on Gist https://gist.github.com/Imron02/5690519 Source: http://www.codefactorycr.com [...]

Leave a Reply
Your email address will not be published. Required fields are marked * Name *

E-mail *

Website

Comment

Post Comment

converted by Web2PDFConvert.com

Latest Blog Entries Create a test project with Selenium2, TestNG and Maven Custom Rules for JQuery Validation in Forms Simple Login with CodeIgniter in PHP Setting up Glassfish behind Apache Apache Tomcat and APR in a Linux Server

2013 Code Factory

Responsive Theme powered by WordPress

converted by Web2PDFConvert.com

Вам также может понравиться