Pages

User Registration with Codeigniter

Sunday, May 20, 2012
In this tutorial, I will explain you user registration with CI. If you are a very newbies in CI, you can start by reading How to start with CI? or read this excellent article Everything You Need to Get Started With CodeIgniter.

If you have finished our previous tutorial, we can start this tutorial now. The CI classes we have to learn in this tutorial are session and form validation. I believe that you would be familiar with PHP session.

Requirement

Download the latest CI version from the following link.

CodeIgniter

Step 1:Configuration

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = "localhost";

$config['username'] = "myusername";

$config['password'] = "mypassword";

$config['database'] = "mydatabase";

$config['dbdriver'] = "mysql";

 

Then open application/config/config.php

$config['base_url'] = 'http://localhost/ci_user';

$config['encryption_key'] = '1234';

 

Open application/config/autoload.php

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

and

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

 

Open application/config/routes.php, change default controller to user controller as we’ll create later on this tutorial.

$route['default_controller'] = 'user';

Step 2:Creating User table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.
CREATE TABLE `user` (
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

Step 3:Creating our Controller

Create a blank document in the controller file (application -> controller) and name it user.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
 public function __construct()
 {
  parent::__construct();
  $this->load->model('user_model');
 }
 public function index()
 {
  if(($this->session->userdata('user_name')!=""))
  {
   $this->welcome();
  }
  else{
   $data['title']= 'Home';
   $this->load->view('header_view',$data);
   $this->load->view("registration_view.php", $data);
   $this->load->view('footer_view',$data);
  }
 }
 public function welcome()
 {
  $data['title']= 'Welcome';
  $this->load->view('header_view',$data);
  $this->load->view('welcome_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function login()
 {
  $email=$this->input->post('email');
  $password=md5($this->input->post('pass'));

  $result=$this->user_model->login($email,$password);
  if($result) $this->welcome();
  else        $this->index();
 }
 public function thank()
 {
  $data['title']= 'Thank';
  $this->load->view('header_view',$data);
  $this->load->view('thank_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function registration()
 {
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
  $this->form_validation->set_rules('email_address', 'Your Email', 'trim|required|valid_email');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
  $this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');

  if($this->form_validation->run() == FALSE)
  {
   $this->index();
  }
  else
  {
   $this->user_model->add_user();
   $this->thank();
  }
 }
 public function logout()
 {
  $newdata = array(
  'user_id'   =>'',
  'user_name'  =>'',
  'user_email'     => '',
  'logged_in' => FALSE,
  );
  $this->session->unset_userdata($newdata );
  $this->session->sess_destroy();
  $this->index();
 }
}
?>
In the index() function,

if(($this->session->userdata('user_name')!=""))

the above code is equal to the following code in php.

if($_SESSION['user_name']!="")

It means that if the user_name is not equal to the null, this user have already logged in. So we will go to welcome() function. Else we will show registration from view.

You will understand next login() and thank() functions I think.

In the registration() function, firstly we load the form_validation library. And then we set the rules for our form field. The trim rule is equal to the php trim() function and you will understand the others I think. And then we run the form validation. If the result is false, we will go to index() function. Else we will add user data and will go to thank() function.

In the logout() function, we will unset and destroy the session data and will go to the index() function.

Step 4:Creating Model

Create a blank document in the model file (application -> model) and name it user_model.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 function login($email,$password)
 {
  $this->db->where("email",$email);
  $this->db->where("password",$password);

  $query=$this->db->get("user");
  if($query->num_rows()>0)
  {
   foreach($query->result() as $rows)
   {
    //add all data to session
    $newdata = array(
      'user_id'  => $rows->id,
      'user_name'  => $rows->username,
      'user_email'    => $rows->email,
      'logged_in'  => TRUE,
    );
   }
   $this->session->set_userdata($newdata);
   return true;
  }
  return false;
 }
 public function add_user()
 {
  $data=array(
    'username'=>$this->input->post('user_name'),
    'email'=>$this->input->post('email_address'),
    'password'=>md5($this->input->post('password'))
  );
  $this->db->insert('user',$data);
 }
}
?>
In the login() function,

$this->db->where("email",$email);

$this->db->where("password",$password);

the above two line will produce the following query in MySQL:

WHERE email='$email' AND password='$password'

$this->session->set_userdata($newdata);

This above code will set our user data to the session variable.

Step 5:Designing our view files

Create a blank document in the views file (application -> views) and name it header_view.php, in the document add all the following code.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
 <div id="wrapper">
Create a blank document in the views file (application -> views) and name it footer_view.php, in the document add all the following code.
<div id="footer">
  &copy; 2011 <a href="http://tutsforweb.blogspot.com/">TutforWeb</a> All Rights Reserved.
 </div><!-- <div class="footer">-->
 </div><!--<div id="wrapper">-->
</body>
</html>
Now let's create our registration view file.

I will use the tableless form design. It has some benefits:

1.Faster loading of pages

2.Efficiency

3.Consistency

4.SEO advantage

5.Layouts and design sophistication

6.Bandwidth efficiency

Create a blank document in the views file (application -> views) and name it registration_view.php, in the document add all the following code.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="password">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<div class="reg_form">
<div class="form_title">Sign Up</div>
<div class="form_sub_title">It's free and anyone can join</div>
 <?php echo validation_errors('<p class="error">'); ?>
 <?php echo form_open("user/registration"); ?>
  <p>
  <label for="user_name">User Name:</label>
  <input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
  </p>
  <p>
  <label for="email_address">Your Email:</label>
  <input type="text" id="email_address" name="email_address" value="<?php echo set_value('email_address'); ?>" />
  </p>
  <p>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" value="<?php echo set_value('password'); ?>" />
  </p>
  <p>
  <label for="con_password">Confirm Password:</label>
  <input type="password" id="con_password" name="con_password" value="<?php echo set_value('con_password'); ?>" />
  </p>
  <p>
  <input type="submit" class="greenButton" value="Submit" />
  </p>
 <?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">-->
In this view we echo our validation errors like below.

<?php echo validation_errors('<p>'); ?>

In our input fields, we use the below function.

<?php echo set_value('user_name'); ?>

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.

Below code is thank_view.php and welcome_view.php.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="pass">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<h1>Thank!</h1>
</div><!--<div id="content">-->
<div class="content">
  <h2>Welcome Back, <?php echo $this->session->userdata('username'); ?>!</h2>
  <p>This section represents the area that only logged in members can access.</p>
  <h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
</div><!--<div class="content">-->
We need some css code to design our registration form. Copy following code and paste your css>style.css.
@charset "utf-8";
/* CSS Document */
body{
background-color:#FFF;
font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
font-size:16px;
text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
width:960px;
margin:0 auto;
}
#content{
width:960px;
margin:5px;
float:left;
}
/************************************************/
.signup_wrap{
height:25px;
width:100%;
padding:5px;
background-color:#2A1FFF;
}
.signin_form{
float:right;
}
.signin_form input{
width:80px;
}
.reg_form{
width:460px;
padding:20px;
margin:0 auto;
border:3px solid #DFDFDF;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbd4e5));
background: -moz-linear-gradient(top,  #fff,  #cbd4e5);
filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff', endColorstr='#cbd4e5');
}
.form_title,
.form_sub_title{
font-size:20px;

font-family:"Lucida Grande",Tahoma,Verdana,Arial,sans-serif;
font-size:20px;
font-weight:bold;
}
.form_sub_title{
font-weight:normal;
padding:6px 0 15px 0;
}
.reg_form p{
width: 300px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 155px; /*width of left column containing the label elements*/
border-top: 1px dashed gray;
height: 1%;
}
.reg_form label{
font-weight: bold;
float: left;
margin-left: -155px; /*width of left column*/
width: 150px; /*width of labels. Should be smaller than left column (155px) to create some right margin*/
}
input{
padding:3px;
color:#333333;
border:1px solid #96A6C5;
margin-top:2px;
width:180px;
font-size:11px;
}
.greenButton{
width:auto;
margin:10px 0 0 2px;
padding:3px 4px 3px 4px;
color:white;
background-color:#589d39;
outline:none;
border:1px solid #006600;
font-weight:bold;
}
.greenButton:active{
background-color:#006600;
padding:4px 3px 2px 5px;
}
.error{
color:#F00;
}
#footer{
color:#fff;
padding-top:20px;
text-align:center;
background: #454546; 
height: 20px;
clear:both;
}
Now our form is finished. Don’t hesitate to ask me, if something goes wrong on your side.
In the next tutorial we will discuss jQuery Ajax with CI.
Download Source Code

102 comments:

  1. GREAT Stuff about Jquery, I wanted to add autocomplete and calendar controls and I found your website very helpful. thanks a lot

    I would add the autocomplete on EDDM Printing and if there is any problem will definitely come back for help
    thanks!!!

    ReplyDelete
  2. Error Number: 1062

    Duplicate entry 'myemail@email.com' for key 'email'
    when email filed is unique on DB.

    ReplyDelete
    Replies
    1. auto increment is missing in ID in database .... tick in auto increment

      Delete
  3. when i run the this code with my url path
    http://localhost/ci/index.php/user
    i got an error like this.
    Parse error: syntax error, unexpected 'function_construct' (T_STRING), expecting variable (T_VARIABLE) in C:\xampp\htdocs\ci\application\controllers\user.php on line 4

    ReplyDelete
    Replies
    1. you dont need to use the index.php file the path should be localhost/ci_user/

      Delete
  4. my code ruin properly but i am able to seen registration page it's show me....

    Welcome Back, !

    This section represents the area that only logged in members can access.
    Logout

    ReplyDelete
  5. Nice tutorial, thanks!
    One question: after registering the user is sent to the thank page. When refreshing the thank page in the browser, the browser asks if the form should be sent again. That shouldn't happen, I think. How do I prevent the browser from asking this?

    ReplyDelete
  6. Thanks! You really saved my time! good tutorial

    ReplyDelete
  7. Thank you sir for such a good tutorial it really saved my time and efforts. i appreciate your work.

    thanks

    ReplyDelete
  8. Don’t hesitate to ask him, if something goes wrong on our side.

    but where is her reply ???????

    I m facing this Problem.

    if you can solve please send the answer to info@WorldQuotes.in


    Not Found

    The requested URL /ci_user/index.php/user/registration was not found on this server.

    ReplyDelete
  9. very good tutorial.Really helped me

    ReplyDelete
  10. Only thing I think this tut is missing would be the idea of making sure the new user is unique. In a normal application of this we do not want users with the same username / email .

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. I am beginner to CI,I have done all the thing said above , "Welcome to CodeIgniter!" is my home page now what to do..?

    ReplyDelete
  13. Hi, one quick question.

    Does this code protect against SQL injection?

    ReplyDelete
  14. Brilliant post, although only minor issue with it, when you are displaying the user as logged in, it should be

    session->userdata('user_name'); ?>

    Thank you anyway!

    ReplyDelete
  15. great tutorial, provide a jump start for me to learn CI

    ReplyDelete
  16. Great, it works,, thank u so much :)

    ReplyDelete
  17. am facing an issue.....when the user logs out he ll be promoted to the registration view....but when he clicks the back button in the browser he ll be able to come back and view the welcome view....can some one please help??

    ReplyDelete
  18. Hey i have done same but its showing Unable to locate the model you have specified: user_model please help me

    ReplyDelete
  19. any idea about the function base_url(); in CI ? its not working and giving me an error althought i have configured $config['base_url'] = 'http://localhost/site/ci';

    ReplyDelete
    Replies
    1. add $this->load->helper('url'); in controllers index function...

      Delete
  20. good tutorial but i think it will be best if each line code is explained.difficult for beginner to understand..

    ReplyDelete
  21. after enter username and password i am not getting anything ..

    ReplyDelete
  22. Thanks a bunch! Works like a charm and pretty easy to follow along with!

    ReplyDelete
  23. how to execute it?? :P m a beginner

    ReplyDelete
  24. nice tutorial sir :D
    i hope you can make also a tutorial for bootstrap and CI...

    ReplyDelete
  25. 404 Page Not Found

    The page you requested was not found.

    ReplyDelete
  26. Thanks a lot..! sir
    but i want jquery validation this form. I need your help

    ReplyDelete
  27. When I hit the submit button, I get redirected to a page that says "This webpage is not available" :(

    ReplyDelete
  28. Thanks brother!!!!!!Very nice this article.....

    ReplyDelete
  29. The requested URL /ci_user/ was not found on this server.

    ReplyDelete
    Replies
    1. Unable to load the requested file: helpers/session_helper.php

      Delete
  30. I'm getting an error everytime I hit the submit and signup buttons. It says
    Object not found!

    The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

    If you think this is a server error, please contact the webmaster.

    Error 404

    localhost
    Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.9

    ReplyDelete
  31. Hi There ..Thanks A Lot For Your Article ..It's Very Helpful ..Nice Share

    Sedekah
    Makassar
    Tas Kulit

    ReplyDelete
  32. working but it is not display any error msg when there is error
    thank u

    ReplyDelete
  33. EMAILPASSWORDSUPPORT has been a leading service provider when it comes to web communications. They have been chosen by the customers as the number one EMAILPASSWORDSUPPORT customer service providers across United States of America and Europe. It is a new EMAILPASSWORDSUPPORT customer service which helps to solve the problems which one has to face on a very frequent basis.
    Email Password Reset Support | Password Recovery Support

    ReplyDelete
  34. Nice Tutorial....I got useful information from this tutorial...Here is also a way to find Simple registration form using codeigniter

    ReplyDelete
  35. thanx thats working!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    ReplyDelete
  36. helpful for beginners,,
    Thanx.....

    ReplyDelete
  37. the css is not at all working for me..what shud i do???

    ReplyDelete
  38. when i run this tutorial it just showing "welcome to userAdministration Controller" on screen how to make it run.

    ReplyDelete
  39. i need Login automatically after registration using for codeigniter

    ReplyDelete
  40. Object not found!

    The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

    If you think this is a server error, please contact the webmaster.

    Error 404

    localhost
    01/02/15 16:32:04
    Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1

    ReplyDelete
  41. after enter username and password i am not getting anything ..

    ReplyDelete
  42. http://localhost:8080/ci_user/

    Error :- ( ! ) Fatal error: Call to undefined function base_url() in C:\wamp\www\ci_user\application\views\header_view.php on line 6 Call Stack #TimeMemoryFunctionLocation 10.0010256160{main}( )..\index.php:0 20.0040314056require_once( 'C:\wamp\www\ci_user\system\core\CodeIgniter.php' )..\index.php:202 30.04302283056call_user_func_array:{C:\wamp\www\ci_user\system\core\CodeIgniter.php:359} ( )..\CodeIgniter.php:359 40.04302283296User->index( )..\CodeIgniter.php:359 50.04302283896CI_Loader->view( )..\user.php:16 60.04302284792CI_Loader->_ci_load( )..\Loader.php:419 70.04402309368include( 'C:\wamp\www\ci_user\application\views\header_view.php' )..\Loader.php:833

    please help me to rectify the above error..plz reply

    ReplyDelete
  43. Thank you so much it is working :D

    ReplyDelete

  44. A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: user::$session

    Filename: controllers/user.php

    Line Number: 10
    wat to do now?

    ReplyDelete
  45. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  46. bad tutorial. if you use the names of the files as stated in this page, you will get a ton of error if you are in a LAMP envoirnment, where filenames are case sensitive. You'll need to rename the filenames with first capitol letter.

    ReplyDelete
  47. Hey i have done same but its showing Unable to locate the model you have specified: user_model please help me

    ReplyDelete

  48. A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: User::$sesssion

    Filename: controllers/user.php

    Line Number: 11

    ReplyDelete
  49. Unable to access an error message corresponding to your field name User Name.(xss_clean)

    ReplyDelete
  50. I'M GETTING THIS FOLLOWING ERROR
    The requested URL /ci_user/index.php/user/registration was not found on this server.

    ReplyDelete
  51. I'M GETTING THIS FOLLOWING ERROR
    The requested URL /ci_user/index.php/user/registration was not found on this server.

    ReplyDelete
  52. I'M GETTING THIS FOLLOWING ERROR
    The requested URL /ci_user/index.php/user/registration was not found on this server.

    ReplyDelete
  53. i want to run registration function please send me url of that

    ReplyDelete
  54. Unable to access an error message corresponding to your field name User Name.(xss_clean) plz help me

    ReplyDelete
    Replies
    1. it can be resolve easily by just putting this
      $autoload['helper'] = array('url','form','security');

      in your autoload file located in config folder
      hope this help

      Delete
  55. i am verify the user register the email set php code.

    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

    CREATE TABLE IF NOT EXISTS `user` (
    `id` int(12) NOT NULL AUTO_INCREMENT,
    `fname` varchar(30) NOT NULL,
    `lname` varchar(30) NOT NULL,
    `email` varchar(60) NOT NULL,
    `password` varchar(40) NOT NULL,
    `status` bit(1) NOT NULL DEFAULT b'0',
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

    hadoop training in chennai | aws training in chennai | informatica training in chennai

    ReplyDelete
  56. 404 error. How an i resolve ??

    ReplyDelete
  57. GREAT, ONE WORD... THANK THANK THANK YOU !!!

    ReplyDelete
  58. I have read your information its very useful topic for me. Thanks for providing information. asp.net training in jalandhar

    ReplyDelete
  59. Nice and very informative post about of website development courses and all the point describe step by step. Thanks for sharing. Keep sharing!!! I feel strongly about it and love learning more on this topic. It is extremely helpful for me. https://goo.gl/YXYcsl

    ReplyDelete
  60. Great point you make there. good POST.. I like your perspective on this subject. straight bevel gears

    ReplyDelete
  61. Thank for sharing you are good information provide use from this blog.
    Hire PHP Developers

    ReplyDelete
  62. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from Pprogramming

    ReplyDelete
  63. Nice,, code Background black and code also in black font color,, Lol

    ReplyDelete
  64. Excellent post..For a real time Dot Net Training | J2EE Training landed at Gangboard.

    ReplyDelete
  65. sir username not display on welcome page wht i can do>>>?

    ReplyDelete
  66. Thank for sharing you are good information provide use from this blog.
    selenium training in chennai

    ReplyDelete
  67. it's informative article for software development. Thanks for sharing.
    Custom software company India

    ReplyDelete
  68. SAS Training in Chennai thank for sharing valuable information .SAS provide integrated process for analyzing business data from every source and gain predictive power to drive performance at every level.

    ReplyDelete
  69. i wondered keep share this sites .if anyone wants realtime training Greens technolog chennai in Adyar visit this blog..
    qlikview training in chennai

    ReplyDelete