RSS

User Registraion with CodeIgniter

28 Mar

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://www.webinone.net/">WebInOne</a> All Rights Reserved.
    </div><!--    <div>-->
    </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>-->
</div><!--<div>-->
<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>-->
</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>-->
</div><!--<div>-->
<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>-->

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.

 
Leave a comment

Posted by on March 28, 2012 in CodeIgniter

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: