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

40 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
  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
  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