আগামী ৩০ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Build a Full Featured Login and Registration System With CodeIgniter

In this tutorial, I will explain you Full Featured user login and registration System with CodeIgniter 2.x. While developing a Web application, you should need a login and registration system as the bare minimum for security. In this article, I explain how you can develop a user login authentication and user Registration system using the CodeIgniter framework. I am assuming that you know the basic file / folder structure of the CodeIgniter framework.

The steps that must be done to make the Login and Registration System is

1. Setting Base Url Configuration

Open config.php within application\config. Set config like below:

Setting CodeIgniter Base Url

Now set Encryption key in your config.php file to CodeIgniter use session library

Set Encryption Key for CodeIgniter session Library2. Create Two folder css and images/captcha within you Project folder. The css folder store your style.css file and images/captcha folder store captcha images.

3. Setting Database Configuration

Open database.php within codeigniter\application\config. Set config like below:

Setting CodeIgniter Database Configuration

Make sure, it matches with your database.

Preparing Database

We will learn about showing data from database in CodeIgniter. But, before that, we prepare a database for practice. This post creates a database named “ci_reg” and a table named “users”. We use phpMyAdmin for easy.

  1. Open your phpmyadmin.
  2. Enter database name “ci_reg” in create new database field.
  3. Click Create button. Your database will be created.

Now Create table “users” by running this query in your sql window:

CREATE TABLE IF NOT EXISTS `users` (

`ID` int(10) NOT NULL AUTO_INCREMENT,

`name` varchar(100) NOT NULL,

`email` varchar(225) CHARACTER SET utf8 NOT NULL,

`username` varchar(30) CHARACTER SET utf8 NOT NULL,

`password` varchar(50) CHARACTER SET utf8 NOT NULL,

`country` varchar(100) NOT NULL,

`address` varchar(100) NOT NULL,

`gender` varchar(20) NOT NULL,

`salt` varchar(50) CHARACTER SET utf8 NOT NULL,

PRIMARY KEY (`ID`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

And Create table “captcha” by running this query in your sql window:

CREATE TABLE IF NOT EXISTS `captcha` (

`captcha_id` bigint(13) unsigned NOT NULL AUTO_INCREMENT,

`captcha_time` int(10) unsigned NOT NULL,

`ip_address` varchar(16) NOT NULL DEFAULT '0',

`word` varchar(20) NOT NULL,

PRIMARY KEY (`captcha_id`),

KEY `word` (`word`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Create Your Controller for showing default home page

Customize your welcome.php controller file (application -> controller), in the document Replace the following code.

<?php
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library(array('session'));

$this->load->model(array('CI_auth', 'CI_menu'));

}

function index()

{

$data = array(

'menu_top' => $this->CI_menu->menu_top(),

);

$this->load->view('welcome_message', $data);

}

}

/* End of file welcome.php */

/* Location: ./system/application/controllers/welcome.php */

This above code and in constructor method we load CodeIgniter session library and load ci_auth and ci_menu model the ci_auth and ci_menu models we will create latter.

Now, we begin create a model for showing menus and checking login status if $this->CI_auth->check_logged() == true? Then we show only $menu_logged array menus otherwise we show $menu_unlogged menus.

Create “ci_menu.php” within codeigniter\application\models. Write following code:

<?php
class CI_menu extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->database();
$this->load->helper('url');
$this->load->model(array('CI_auth'));
}

function create_menu($array_menu, $separator ='|'){
$data = array(
'menu' => $array_menu,
'separator' => $separator
);
return $this->load->view('_links',$data, true);
}

function menu_top(){
$menu_common = array(
'Home' => base_url(),
'People' => '#',
'News' => '#'
);

$menu_unlogged = array(
'Register' => base_url().'index.php/register/',
'Login' => base_url().'index.php/login/'
);

$menu_logged = array(
'My Account' => base_url().'index.php/member_area/',
'Logout' => base_url().'index.php/login/logout/'
);

$menu = array_merge($menu_common,($this->CI_auth->check_logged() == true)?$menu_logged:$menu_unlogged);
return $this->create_menu($menu);
}

}

Create _links.php” within codeigniter\application\views for show menus in your page. Write following code:

<?php foreach($menu as $link_text=>$link_url):?>

 <?php echo $separator; ?>

<?php endforeach; ?>

Create ci_auth.php” for user login authentications within codeigniter\application\models. Write following code:

<?php
class CI_auth extends CI_Model {

function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->database();
$this->load->helper('url');
$this->load->model(array('CI_encrypt'));
}

function process_login($login_array_input = NULL){
if(!isset($login_array_input) OR count($login_array_input) != 2)
return false;
//set its variable
$username = $login_array_input[0];
$password = $login_array_input[1];
// select data from database to check user exist or not?
$query = $this->db->query("SELECT * FROM `users` WHERE `username`= '".$username."' LIMIT 1");
if ($query->num_rows() > 0)
{
$row = $query->row();
$user_id = $row->ID;
$user_pass = $row->password;
$user_salt = $row->salt;
if($this->CI_encrypt->encryptUserPwd( $password,$user_salt) === $user_pass){
$this->session->set_userdata('logged_user', $user_id);
return true;
}
return false;
}
return false;
}

function check_logged(){
return ($this->session->userdata('logged_user'))?TRUE:FALSE;
}


function logged_id(){
return ($this->check_logged())?$this->session->userdata('logged_user'):'';
}
}


This above code process_login functions process from the login form and checked_logged function to whether or not the user has logged? The last function logged_id returns the id for the user who is currently logged in

Create ci_encrypt.php” for user password encryption and within codeigniter\application\models. Write following code:

<?php
class CI_encrypt extends CI_Model {

function __construct()
{
parent::__construct();
}

// Generate Random Digit
function genRndDgt($length = 8, $specialCharacters = true) {
$digits = '';
$chars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";

if($specialCharacters === true)
$chars .= "!?=/&+,.";


for($i = 0; $i < $length; $i++) {
$x = mt_rand(0, strlen($chars) -1);
$digits .= $chars{$x};
}

return $digits;
}

// Generate Random Salt for Password encryption
function genRndSalt() {
return $this->genRndDgt(8, true);
}

// Encrypt User Password
function encryptUserPwd($pwd, $salt) {
return sha1(md5($pwd) . $salt);
}
}

This above code genRndDgt function Generate Random Digit for create salt and genRndSalt create salt using genRndDgt function. The last function encryptUserPwd encrypt user given password.

Customize our default view file welcome_message.php file within application\views. Replace following code:

Welcome to CodeIgniter

<?php
echo $menu_top;
?>
<h1>WELCOME TO CODEIGNITER 2.x</h1>
<pre>

Now try to point your browser to http://localhost/Your_CI_Project_Folder/

login3

Create _output_html.php file within codeigniter\application\views to show common layout. Add following code:

<html>
<head>
<title> CodeIgniter Login and Registration System With Captcha </title>
<link href='<?php echo base_url(). "css/style.css" ?>' rel="stylesheet" type="text/css" />

</head>

<body>
<?php echo $menu_top; ?>
<br/>
<div>
<?php echo $body; ?>
</div>

</body>
</html>

We need some css code to design our registration form. Copy following code and paste your css>style.css.

body {

margin: 0;

padding: 0;

background: #f4f4f4;

font: 14px;

font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;

}

.error{

color:red;

}

.link { text-align: center; clear: both; padding: 20px 0; }

.link a { color: #333333; }

.wrapper {

width: 960px;

margin: 50px auto;

}

/* Form 1 style */

.form1 {

width: 450px;

/*float: left;*/

background: #fff;

color: #777;

-webkit-box-shadow: 0px 0px 8px 2px #d1d1d1;

-moz-box-shadow: 0px 0px 8px 2px #d1d1d1;

box-shadow: 0px 0px 8px 2px #d1d1d1;

-webkit-border-top-left-radius: 0px;

-webkit-border-top-right-radius: 0px;

-webkit-border-bottom-right-radius: 6px;

-webkit-border-bottom-left-radius: 6px;

-moz-border-radius-topleft: 0px;

-moz-border-radius-topright: 0px;

-moz-border-radius-bottomright: 6px;

-moz-border-radius-bottomleft: 6px;

border-top-left-radius: 0px;

border-top-right-radius: 0px;

border-bottom-right-radius: 6px;

border-bottom-left-radius: 6px;

overflow: hidden;

}

.formtitle {

padding: 10px;

line-height: 16px;

font-size: 13px;

text-shadow: -1px -1px #e87c19;

color: #fff;

font-weight: bold;

border-bottom: 1px solid #eb8d19;

width: 510px;

background: #ffbd27; /* Old browsers */

background: -moz-linear-gradient(top, #ffbd27 0%, #ffb119 50%, #ff9d19 51%, #ff9d19 100%); /* FF3.6+ */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffbd27), color-stop(50%,#ffb119), color-stop(51%,#ff9d19), color-stop(100%,#ff9d19)); /* Chrome,Safari4+ */

background: -webkit-linear-gradient(top, #ffbd27 0%,#ffb119 50%,#ff9d19 51%,#ff9d19 100%); /* Chrome10+,Safari5.1+ */

background: -o-linear-gradient(top, #ffbd27 0%,#ffb119 50%,#ff9d19 51%,#ff9d19 100%); /* Opera11.10+ */

background: -ms-linear-gradient(top, #ffbd27 0%,#ffb119 50%,#ff9d19 51%,#ff9d19 100%); /* IE10+ */

filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffbd27', endColorstr='#ff9d19',GradientType=0 ); /* IE6-9 */

background: linear-gradient(top, #ffbd27 0%,#ffb119 50%,#ff9d19 51%,#ff9d19 100%); /* W3C */

}

.input {

width: 510px;

border-bottom: 1px solid #ddd;

margin-bottom: 10px;

margin: 20px;

overflow: hidden;

}

.inputtext {

float: left;

line-height: 18px;

height: 35px;

font-size: 14px;

width: 155px;

}

.inputcontent {

float: left;

width: 290px;

height: 40px;

}

.inputcontent input {

padding: 5px;

height: 30px;

width: 200px;

line-height: 18px;

border: 1px solid #c7c7c7;

-moz-border-radius:6px;

-webkit-border-radius:6px;

border-radius:6px;

color: #777;

}

.inputcontent a {

color: #0084ff;

font-size: 12px;

text-decoration: none;

line-height: 12px;

}

.nobottomborder {

border-bottom: 0;

}

.orangebutton {

background: #ffc339; /* Old browsers */

background: -moz-linear-gradient(top, #ffc339 0%, #ff9b19 100%); /* FF3.6+ */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffc339), color-stop(100%,#ff9b19)); /* Chrome,Safari4+ */

background: -webkit-linear-gradient(top, #ffc339 0%,#ff9b19 100%); /* Chrome10+,Safari5.1+ */

background: -o-linear-gradient(top, #ffc339 0%,#ff9b19 100%); /* Opera11.10+ */

background: -ms-linear-gradient(top, #ffc339 0%,#ff9b19 100%); /* IE10+ */

filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffc339', endColorstr='#ff9b19',GradientType=0 ); /* IE6-9 */

background: linear-gradient(top, #ffc339 0%,#ff9b19 100%); /* W3C */

border: 1px solid #ff9b19;

-webkit-border-radius: 20px;

-moz-border-radius: 20px;

border-radius: 20px;

line-height: 20px;

font-size: 16px;

padding: 6px 12px;

color: #fff;

text-shadow: -1px -1px #ff9b19;

float: right;

margin-left: 10px;

cursor: pointer;

}

.orangebutton:hover{

background: #ff9b19; /* Old browsers */

background: -moz-linear-gradient(top, #ff9b19 0%, #ffc339 100%); /* FF3.6+ */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ff9b19), color-stop(100%,#ffc339)); /* Chrome,Safari4+ */

background: -webkit-linear-gradient(top, #ff9b19 0%,#ffc339 100%); /* Chrome10+,Safari5.1+ */

background: -o-linear-gradient(top, #ff9b19 0%,#ffc339 100%); /* Opera11.10+ */

background: -ms-linear-gradient(top, #ff9b19 0%,#ffc339 100%); /* IE10+ */

filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff9b19', endColorstr='#ffc339',GradientType=0 ); /* IE6-9 */

background: linear-gradient(top, #ff9b19 0%,#ffc339 100%); /* W3C */

}

/* Form 2 Style */

.form2 {

width: 510px;

/*float: right;*/

background: #fff;

color: #777;

-webkit-box-shadow: 0px 0px 8px 2px #d1d1d1;

-moz-box-shadow: 0px 0px 8px 2px #d1d1d1;

box-shadow: 0px 0px 8px 2px #d1d1d1;

-webkit-border-top-left-radius: 0px;

-webkit-border-top-right-radius: 0px;

-webkit-border-bottom-right-radius: 6px;

-webkit-border-bottom-left-radius: 6px;

-moz-border-radius-topleft: 0px;

-moz-border-radius-topright: 0px;

-moz-border-radius-bottomright: 6px;

-moz-border-radius-bottomleft: 6px;

border-top-left-radius: 0px;

border-top-right-radius: 0px;

border-bottom-right-radius: 6px;

border-bottom-left-radius: 6px;

overflow: hidden;

}

.textarea {

padding: 5px;

height: 80px;

width: 200px;

line-height: 18px;

border: 1px solid #c7c7c7;

-moz-border-radius:6px;

-webkit-border-radius:6px;

border-radius:6px;

color: #777;

}

.inputtextbox {

width: 510px;

border-bottom: 1px solid #ddd;

margin-bottom: 10px;

margin: 20px;

overflow: hidden;

}

.inputtextbox .inputcontent {

height: 100px;

}

.buttons {

padding: 15px;

height: 34px;

}

Create ci_captcha.php” for generate captcha image it protect spammers, go application\models. Write following code:

<?php
class CI_captcha extends CI_Model {
function __construct()
{
parent::__construct();
}

function make_captcha()
{
$this -> load -> helper('captcha');
$vals = array(
'img_path' => './/images/captcha/', // PATH for captcha ( *Must mkdir (htdocs)/captcha )
'img_url' => base_url().'/images/captcha/', // URL for captcha img
'img_width' => 120, // width
'img_height' => 50, // height
'font_path'     => '../system/fonts/texb.ttf',
'expiration' => 3600 ,
);
// Create captcha
$cap = create_captcha( $vals );
// Write to DB
if ( $cap ) {
$data = array(
'captcha_id' =>'',
'captcha_time' => $cap['time'],
'ip_address' => $this -> input -> ip_address(),
'word' => $cap['word'] ,
);
$query = $this -> db -> insert_string( 'captcha', $data );
$this -> db -> query( $query );
}else {
return "Captcha not work" ;
}
return $cap['image'] ;
}

function check_captcha()
{
// Delete old data ( 2hours)
$expiration = time()-3600 ;
$sql = " DELETE FROM captcha WHERE captcha_time < ? ";
$binds = array($expiration);
$query = $this->db->query($sql, $binds);

//checking input
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();

if ( $row -> count > 0 )
{
return true;
}
return false;

}

}//endofclass

?>

This above code we load captcha helper for generating captcha image. The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images. For more details you can see CodeIgniter captcha documentation.

Now let’s create our registration view _join_form.php file to view registration form, within application\views. Write following code:

<div>
<div> Join now, please fill in the form below</div>


<?php echo form_open(base_url()."index.php/register/")?>
<span><?php echo $captcha_return?><?php echo validation_errors() ?></span>
<div>
<div>Your Name: </div>
<div>
<input type="text" name="name" value="<?php echo set_value('name') ?>" />
</div>
</div>
<div>
<div>Your Username</div>

<div>
<input type="text" name="username" value="<?php echo set_value('username') ?>" />
</div>
</div>

<div>
<div>Your Password</div>
<div>
<input type="password" name="password" value="<?php echo set_value('password') ?>" />
</div>
</div>

<div>
<div>Confirm Your Password</div>
<div>
<input type="password" name="passconf" value="<?php echo set_value('passconf') ?>" />
</div>
</div>
<div>
<div>Your Email</div>
<div>
<input type="text" name="email" value="<?php echo set_value('email') ?>" />
</div>
</div>
<div>
<div>Country</div>

<select name="country">
<option value="">Select Country</option>
<option value="Bangladesh" <?php echo set_select('country', 'Bangladesh'); ?> >Bangladesh</option>
<option value="Bangladesh" <?php echo set_select('country', 'India'); ?> >India</option>
<option value="Bangladesh" <?php echo set_select('country', 'Pakistan'); ?> >Pakistan</option>
<option value="Bangladesh" <?php echo set_select('country', 'Nepal'); ?> >Nepal</option>
<option value="Bangladesh" <?php echo set_select('country', 'Bhutan'); ?> >Bhutan</option>
<option value="Bangladesh" <?php echo set_select('country', 'Srilanka'); ?> >Srilanka</option>

</select>

</div>

<div>
<div>Your Address</div>
<div>
<textarea name="address"><?php echo set_value('address') ?></textarea>
</div>
</div>
<div>
<div>Your Gender</div>

<input type="radio" name="gender" value="Female"  <?php echo set_radio('gender', 'Male'); ?> /> Male &nbsp;&nbsp;   <input type="radio" name="gender" value="Male"  <?php echo set_radio('gender', 'Female'); ?> />   Female

</div>

<div>
Type the Captcha number below:<br /><br />

<?php echo $cap_img; ?>
<input  type="text" name="captcha" value=""/>
</div>
<div >
<input type="checkbox" name="terms" value="1" <?php echo set_checkbox('terms', '1'); ?> />I agree to the w3programmers Terms of Service and Privacy Policy
</div>
<div><input type="submit" value="Submit" name="submit"/></div>

</div>
<?php echo form_close()?>
</body>
</html>

In this view we echo our validation errors like below.

<?php echo validation_errors(); ?>

In our input fields, we use the below functions.

set_value(), set_select(), set_radio() and set_checkbox() functions, for showing captcha we also use $cap_img variable that we already set in our register controller.

Because of above function the original data will be show in the form, if there is an error after the validation rules. So we have only been dealing with errors.

Now we create “register.php” controller for user registration, within codeigniter\application\controller. Write following code:

<?php
class Register extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('form_validation'));
$this->load->model(array('CI_captcha', 'CI_menu', 'CI_encrypt'));
$this->load->helper(array('form', 'url'));
$this->load->database();
}

function index(){
if($this->CI_auth->check_logged()=== true)
redirect(base_url().'member_area/');

$data['title'] = 'CodeIgniter Registration System';
$data['menu_top'] = $this->CI_menu->menu_top();
$sub_data['captcha_return'] ='';
$sub_data['cap_img'] = $this ->CI_captcha->make_captcha();
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'User name', 'trim|required|alpha_dash|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[3]|max_length[20]|matches[passconf]|xss_clean');
$this->form_validation->set_rules('passconf', 'Confirm Password', 'trim|required|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email',  'trim|required|min_length[3]|max_length[30]|valid_email');
$this->form_validation->set_rules('country', 'Country', 'trim|required|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|xss_clean');
$this->form_validation->set_rules('terms', 'Terms of Sevices', 'trim|required|xss_clean');
$this->form_validation->set_rules('captcha', 'Captcha', 'required');

// Set Custom messages
//$this->form_validation->set_message('required', 'Your custom message here');


if ($this->form_validation->run() == FALSE){
$data['body']  = $this->load->view('_join_form', $sub_data, true);
}
else{
if($this->CI_captcha->check_captcha()==TRUE){
$name = $this->input->post('name');
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
$country = $this->input->post('country');
$address = $this->input->post('address');
$gender = $this->input->post('gender');
$terms = $this->input->post('terms');
$check_query = "SELECT * FROM `users` WHERE `username`='$username' OR `email`='$email'";
$query = $this->db->query($check_query);
if ($query->num_rows() > 0){
$sub_data['captcha_return'] = 'username or email address you entered is already used by another, please change<br/>';
$data['body']  = $this->load->view('_join_form', $sub_data, true);
}
else{
$rand_salt = $this->CI_encrypt->genRndSalt();
$encrypt_pass = $this->CI_encrypt->encryptUserPwd( $this->input->post('password'),$rand_salt);
$input_data = array(
'name' => $name,
'username' => $username,
'email' => $email,
'password' => $encrypt_pass,
'country' => $country,
'address' => $address,
'gender' => $gender,
'salt' => $rand_salt
);
if($this->db->insert('users', $input_data)){
$data['body']  = "Registration success, please login<br/>";
}
else
$data['body']  = "error on query";
}
}
else{
$sub_data['captcha_return'] = "The characters you entered didn't match the word verification. Please try again. <br/>";
$data['body']  = $this->load->view('_join_form', $sub_data, true);
}
}

}
else{
$data['body']  = $this->load->view('_join_form', $sub_data, true);
}
$this->load->view('_output_html', $data);

}
}
?>

In the construct() function, firstly we load the form_validation library. In index function if($this->CI_auth->check_logged()=== true) this means the user have already logged in. So we will go to our member area. Else we will show registration from view. And then we set the rules for our form field.

Now try to point your browser to http://localhost/Your_CI_Project_Folder/index.php/register or go to your project just click your register menu

CodeIgniter Registration Form

If you submit your registration form with invalid information or blank input you will just see like below

CodeIgniter Registration Form Validation

After successfully Registration you see as like below picture:

CodeIgniter Registration Success

Now we begin Create Login System:

Firstly, we begin create a login form for user login system “_login_form.php” within codeigniter\application\views. Write following code:

<div>
<?php echo form_open(base_url().'index.php/login/')?>
<div>Login to your account</div>
<?php echo validation_errors(); ?>
<span><b><?php echo $login_failed; ?></b></span>

<div>
<div>Username Or Email: </div>
<div>
<input type="text" name="username" value="<?php echo set_value('username'); ?>"/>

</div>
</div>

<div>
<div>Password: </div>
<div>

<input type="password" name="password" value="<?php echo set_value('password'); ?>" /><br/>
</div>
</div>

<div>
<input type="submit" value="Submit" name="submit_login"/>
</div>

<?php echo form_close()?>
</div>

Then we create “login.php” for user login authentications, form field validation and sanitization within codeigniter\application\controller. Write following code:

<?php

class Login extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->model(array('CI_auth', 'CI_menu'));
$this->load->helper(array('html','form', 'url'));
}

function index(){
if($this->CI_auth->check_logged()=== true)
redirect(base_url().'index.php/member_area/');

$sub_data['login_failed'] ='';
$data['title'] = 'Login';
$data['menu_top'] = $this->CI_menu->menu_top();
$data['body'] = $this->load->view('_login_form',$sub_data, true);

if($this->input->post('submit_login')) {
$this->form_validation->set_rules('username', 'username', 'trim|required|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[5]|max_length[35]|xss_clean');
$this->form_validation->set_error_delimiters('<div style="color:red;">', '</div>');

if ($this->form_validation->run() == FALSE){
$data['body'] = $this->load->view('_login_form',$sub_data , true);
$this->load->view('_output_html', $data);
}
else{
$login_array = array($this->input->post('username'), $this->input->post('password'));
if($this->CI_auth->process_login($login_array))
{
//login successfull
redirect(base_url().'index.php/member_area/');
}
else{
$sub_data['login_failed'] = "Invalid username or password";
$data['body'] = $this->load->view('_login_form',$sub_data , true);
$this->load->view('_output_html', $data);
}
}
}
else{
$this->load->view('_output_html', $data);
}
}
function logout(){
$this->session->sess_destroy();
redirect(base_url().'index.php/login/');
}
}
?>

This above in __construct function first we add our session library and others models and helpers. Then in index function first we check the user already logged or not, if the user already logged in we redirect to our members area, otherwise we validate, sanitize and filter input fields data.

Finally we create member_area.php file within codeigniter\application\controller. Write following code:

<?php

class Member_area extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('session'));
$this->load->model(array('CI_auth', 'CI_menu'));
$this->load->helper(array('html','url'));
}

function index(){
if($this->CI_auth->check_logged()===FALSE)
redirect(base_url().'index.php/login/');
else{
$data['title'] = 'Member only';
$data['menu_top'] = $this->CI_menu->menu_top();
$data['body'] = 'You are logged in MEMBER AREA <br/> <br/> <a href="'.base_url().'login/logout/"> Click here </ a> to logout';
$this->load->view('_output_html', $data);
}
}
}

Now try to point your browser to http://localhost/ci_reg_final/index.php/login/ or go to your project just click your login menu

CodeIgniter Login Form

If you submit your Login form with invalid information or blank input you will just see like below

CodeIgniter Login Validation

After Successfully Login you see like as below picture

CodeIgniter Success Login

So we come to the end of our Full Featured Login and Registration System with CodeIgniter and hope you all understand properly.

hApPy PhP IgNiTeRs 🙂

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i'm a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I'm also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute - a leading Training Institute in the country.
61 comments on “Build a Full Featured Login and Registration System With CodeIgniter
  1. After looking at a handful of the blog posts on your blog, I really appreciate your technique of writing a blog. I bookmarked it to my bookmark site list and will be checking back in the near future. Please visit my web site too and let me know what you think.

  2. Hi there to all, as I am actually keen of reading this website’s post to be updated regularly. It includes nice stuff.

  3. Thanks for this tutorial. Please give me a suggestion, how to create multiple user registration from in a single registration form by using CodeIgniter.

  4. I do not even know how I ended up here, but I thought this post was great.
    I do not know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!

  5. Great web site you have got here.. It’s hard to find excellent writing like yours nowadays. I seriously appreciate individuals like you! Take care!!

  6. Hi, yes this piece of writing is really pleasant and I have learned lot of things from it concerning blogging. thanks.

  7. When some one searches for his required thing, thus he/she wants to be available that in detail, thus that thing is maintained over here.

  8. A PHP Error was encountered

    Severity: Warning

    Message: imagettftext(): Could not read font

    Filename: helpers/captcha_helper.php

    Line Number: 217

    I get this error… how to fix this?

  9. Hi, I modified _links.php by this code, for getting the output you show to us, please let me know if this is the best way according to your tutorial.

    Thanks in forward.

    $link_url):?>

  10. A Database Error Occurred

    Error Number: 1366

    Incorrect integer value: ” for column ‘captcha_id’ at row 1

    INSERT INTO `captcha` (`captcha_id`, `captcha_time`, `ip_address`, `word`) VALUES (”, 1385631547.3981, ‘127.0.0.1’, ‘km1HUX’)

    Filename: E:\Easy\www\ci\system\database\DB_driver.php

    Line Number: 330

    A Database Error Occurred

    Error Number: 1366
    models/ci_captcha.php have problem :
    Incorrect integer value: ” for column ‘captcha_id’ at row 1

    INSERT INTO `captcha` (`captcha_id`, `captcha_time`, `ip_address`, `word`) VALUES (”, 1385631547.3981, ‘127.0.0.1’, ‘km1HUX’)

    Filename: E:\Easy\www\ci\system\database\DB_driver.php

    Line Number: 330
    ——————————————
    solve :
    in line 24

    ‘captcha_id’ =>”,

    TO

    //’captcha_id’ =>”,

    ——————————————-
    logout in my account page have problem :
    controllers/member_area.php
    in line 18 :
    $data[‘body’] = ‘You are logged in MEMBER AREA Click here to logout’;

    TO :

    $data[‘body’] = ‘You are logged in MEMBER AREA Click here to logout’;

    ————————-
    Does not form forget password and refresh button for captcha and change password and edit user profile…

  11. This is a topic that is close to my heart… Many thanks!
    Exactly where are your contact details though?

  12. hai masud..i like your article about CI..many resources i found but this one i like it very much because easy to understand… after setting all this..i got this problem.. could you help me to resolve this?

    | | | | | | | |

    the menu top not appear.. just separator like above…. thanks =p

  13. Dear Masud, thank you and respect for this awesome share. I got partially working your code on my webserver anyway I can’t get fully working because of I can’t download the source files, link broken.

    Alessandro

  14. replace echo $separator in _links.php with echo anchor($link_url,$link_text,”) to get the menu to display instead of | | | | | |

  15. after changing to anchor($link_url,$link_text,”) there is:
    PHP Error was encountered
    Serverity: Notice
    Message: Use of undefined constant …
    Filename:views/_links.php

  16. Hey..cool tutorial! The source codes arent available 🙁
    Can you please email me the source code..it will be very helpfull!!

    Thanks

  17. I have successfully implemented your tutorial and its working thank you for that. I have few doubts, how to add forgot password link and i want add two user roles while registration, based on user role i want to redirect to different page.
    Thank you

  18. Hi, I like your tutorial very much but my concern is the menu is not showing. can you provide help I use WAMP as a server.

    Thank you!

  19. I got the menu to work

    ALIAS
    4 DECEMBER, 2014 AT 5:43 AM
    replace echo $separator in _links.php with echo anchor($link_url,$link_text,”) to get the menu to display instead of | | | | | |

    This is correct except you have to take out the double quotes and comma so it should be

    instead of

    This worked for me

  20. Can you give me a solution why member_area page is not opening and showing this 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

    localhost
    Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16

  21. hellow uor web site is awosam & your tutorial is most helpful…please make a full project using codeignitor
    please do this soon

  22. i tried to download the code but i got this error:

    “The file you’re looking for has been moved or deleted.
    Please see this article for details on why a shared link might stop working.”

  23. The tutorial was awesome but i have a little problem. When I try to register the captcha does not display in the form. Plus when I try to download the source code from drop box I get a 404. Can anyone help?
    Regards
    Theophilus

  24. certainly like your website but you have to test the spelling on several of
    your posts. A number of them are rife with spelling issues and I
    to find it very bothersome to inform the reality
    on the other hand I will definitely come back again.

Leave a Reply

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