Login and Registration Forms in CodeIgniter 3 and MySQL

In this topic, we will create a simple registration and login system in CodeIgniter 3. We will use email id as the login id. There will be a simple home page with options for Signup and Login. Complete the registration by entering the name, email_id and password. Once registration is successful, the customer can login into the application. We will use CodeIgniter 3 and MySQL to develop this application.

Create a MySQL table for customer details

We will create a table named 'customer' in the MySQL database. The table structure is given below:

Table: customer

This table stores details of all customers who completed registration successfully.

create login and registration page in CodeIgniter 3

Below are the columns in this table.

  1. id - It is the primary key and auto-incremented
  2. name - Name of the customer
  3. email - Email Id of the customer
  4. password - Password for login
MySQL create table script for this table is given below.

customer.sql


CREATE TABLE `customer` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `customer`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `customer`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

Create the views for Home, Signup and Login Pages

There are three views for the home page (home.php), signup page (signup.php) and login page (login.php). Additionally, there will be a custom css file and a small piece of JavaScript for showing/hiding the password in the login page. Let us take a look at them one by one.

View for Home Page

Our home page is simple, it just displays two links, one for signup and the other for login. When the customer is logged in, it will display a welcome message with the name of the customer and a logout link. Below are the screens for before login and after login:

Before Login

codeigniter login and registration source code free download

After Login

codeigniter login and registration source code free download

Let's see the code below:

application/views/home.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Customer Signup & Login</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
</head>
<body>
    <div class="container">
        <h1>You are at Home Page </h1>
        <div class="welcome-user">
            <?php $login = $this->session->userdata('login');
            if (isset($login)) { ?>
                <?php echo "Welcome ".$login['name'];?>
                <a class="user" href="<?php echo base_url(); ?>logout">Logout</a>
            <?php } else { ?>
                <a id = "signup"  href="<?php echo base_url();?>signup">Signup</a>
                <a class="user" id = "login"  href="<?php echo base_url();?>login">Login</a>
            <?php } ?>
        </div>
    </div>
</body>
</html>

If session data is set, it displays "Welcome" with the customer name. If session data is not available, it displays two links - Signup and Login.

View for Signup Page

codeigniter login and registration source code

The Signup or Registration page displays a form for the customer to fill out and submit. It has name, email id, password and confirm password fields. Then a submit button. See the below code for the signup page:

application/views/signup.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Customer Signup</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
</head>
<body>
  <div class="container">
    <h2>Customer Signup</h2>
    <p class="error "><?php if ($err_msg != "") { echo $err_msg;}?></p>
    <p class="success"><?php if ($succ_msg !="") {echo $succ_msg;}?></p>
    <form id ="frm" action = "<?php echo base_url()?>signup" method = "post">
      <div class="form-group col-md-12">
        <label>Name</label>
        <input type = "text" name="name" id = "name" class="form-control" maxlength="100" value="<?php echo set_value('name');?>" placeholder="Enter Your Name">
        <span class="error"><?php echo form_error('name'); ?></span>
      </div>
      <div class="form-group col-md-12">
        <label>Email Id</label>
        <input type = "text" name="email" id = "email" class="form-control"  maxlength="100" value="<?php echo set_value('email');?>" placeholder="Enter Your Email">
        <span class="error"><?php echo form_error('email'); ?></span>
      </div>
      <div class="form-group col-md-12">
        <label>Password</label>
        <input type = "password" name="password" id = "password" class="form-control" placeholder="Enter a Password">
        <span class="error"><?php echo form_error('password'); ?></span>
      </div>
      <div class="form-group col-md-12">
        <label>Confirm Password</label>
        <input type = "password" name="conf_pwd" id = "conf_pwd" class="form-control" placeholder="Enter Password again">
        <span class="error"><?php echo form_error('conf_pwd'); ?></span>
      </div>
      <div class="col-md-12 text-center">
        <input type ="submit" name="signup" class="btn btn-primary" value="Submit">
              
         <a href = "<?php echo base_url()?>" class="btn btn-danger" name="login">Cancel</a>
       </div>
     </form>
   </div>
 </body>
 </html>

In the <form> action, it calls signup() method of the customer controller. For each input field validations are done in the Controller and the validation message for each input gets displayed just below the input field in the form.

View for Login Page

codeigniter-login and registration

The login page will have email_id and password as input fields. For each input, an error message will be displayed in case the validation fails. In <form> action, it calls login() method of the controller. See below code for the login view:

application/views/login.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Customer Login</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
<script src="<?php echo base_url('assets/js/scripts.js')?>"></script>
</head>
<body>
	<div class="container">
		<h2>Customer Login</h2>
		<form id ="frm" action = "<?php echo base_url()?>login" method = "post">
			<?php if ($msg !="") { ?>
				<p class="error"><?php echo $msg; $msg ="";?></p>
			<?php } ?>
			<div class="form-group col-md-12">
				<label>Email Id</label>
				<input type = "text" class="form-control" name="email" id = "email" value="<?php echo set_value('email')?>" placeholder ="Enter your Email Id" autofocus>
				<span class="error"><?php echo form_error('email'); ?></span>
			</div>
			<div class="form-group col-md-12">
				<label>Password</label>
				<input type = "password" class="form-control" name="password" id = "password" placeholder ="Enter Password">
				<span class="error"><?php echo form_error('password'); ?></span>
			</div>
			<div class="form-group col-md-12 tgl-pwd">
				<input type="checkbox" class="check" onclick="togglePwd()">Show Password
			</div>
			<div class="form-group col-md-12 login-btn">
				<button type="submit" class="btn btn-primary" name="login">Login</button>      
				<a href = "<?php echo base_url()?>" class="btn btn-danger" name="login">Cancel</a>
			</div>
		</form>
	</div>
</body>
</html>

We will use a JavaScript function for the option "Show Password" which is added as a checkbox in the login form. When the user clicks on it, it calls a JavaScript function togglePwd() defined in scripts.js.

Below is the code for togglePwd() function:

scripts.js


function togglePwd() {
  var pwd = document.getElementById("password");
  if (pwd.type === "password") 
    pwd.type = "text";
  else 
    pwd.type = "password";
}

This function changes the type of the password field in the login page, from "password" to "text" and vice versa.

Let me give the stylesheet also I am using for all these views.

style.css


* {box-sizing: border-box;
}
.container{
  min-height: 700px;
}
h1,h2 {
  margin-top: 50px;
  text-align: center;
}
.welcome-user {
  text-align: center;
  font-size: 20px;
}
.user{
  padding-left: 35px;
}
.login{
  text-align: center;
  font-size: 20px;
}
#frm {
  margin: 50px auto;
  padding-bottom: 30px;
  padding-top: 20px;
  border: 1px solid #09168d;
  border-radius: 7px;
  background: #fff;
  width: 47%;
  }
.tgl-pwd{
  padding: 0;
}
.check {
  width: 10%;
  height: 20px;
  }
label{
  font-weight: bold;
}
.login-btn{
  text-align: center;
}
p.error{
  color: red;
  text-align: center;
  font-size: 20px;
}
p.success{
  color: green;
  text-align: center;
  font-size: 20px;
}
span.error{
  color: red;
  text-align: left;
}

I just added a few simple styles here, you can always add better styles.

So, our views are done, now let's go to the controller section.

Controller code (CustomerController.php)

Our controller function has an index() method to display the home page, signup() method to display and process the signup form, login() method for customer login and a logout() method.

Controller method index()

index() method is executed by default in a controller. In this method, it just loads the view that displays home page.


public function index(){
	$this->load->view('home');
}

Controller Method signup()

It writes CodeIgniter 3 validation rules for each input field in the form. If validation fails for a field, it reloads the view with an error message displayed corresponding to the field for which validation failed. Let's see the code for signup() method.


public function signup() {
$element = [];
$element['succ_msg'] = "";
$element['err_msg'] = "";
if (isset($_POST['signup'])) {
  // get the values of form fields
  $name = $this->input->post('name');
  $email = $this->input->post('email');
  $password = $this->input->post('password');
  $password = md5($password);
  // validate each field
  $this->form_validation->set_rules('name', 'Name', 'trim|required',
    array(
        'required'=>'You must provide a %s')
      );
  $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[customer.email]',
    array(
        'required'=>'You must provide an %s',
        'valid_email' => 'This is not a valid email address',
        'is_unique' => 'This %s already registered')
      );
  $this->form_validation->set_rules('password', 'Password', 'trim|required',
    array(
        'required' => 'You must provide %s')
      );
  $this->form_validation->set_rules('conf_pwd', 'Confirm Password', 'trim|required|matches[password]',
    array(
        'required' => 'You must provide %s',
        'matches'  => 'Passwords do not match') 
      );

  if ($this->form_validation->run() == FALSE) {
    // validation not passed, so load the form again
    $this->load->view('signup',$element);
    
  } 
  else {
  // validations are successful, go for signup
    $data = array('name'=>$name,  'email'=>$email, 'password'=>$password);
    $result = $this->ModelCustomer->signup($data);
    if ($result){
      $msg = 'Signup successful, please <a href="'.base_url().'login">login</a> with your email id and password';
      $element['succ_msg'] = $msg;
    }
    else{
      $msg = "Error in Signup";
      $element['err_msg'] = $msg;
    }	
    $this->load->view('signup',$element);
  }
}
else {	
    $this->load->view('signup', $element);
  }
}  // end of function signup

Validations are performed on the input data using form_validation->set_rules() method. For details on how to do form validation in CodeIgniter 3, you can read the topic How to do Form Validation in CodeIgniter 3.

For successful validation of all fields, it calls Model method signup() which inserts the signup details into a database table and then the registration is complete.

Controller Method login()

Method login() is called when the user clicks on the Login link in the Home page. This method does some validation and then checks with database to see if the credentials match. If a match is found, it sets the email and name in the session and redirects the user to the home page, otherwise, it reloads the login view with the error message. Let's see the code:


public function login(){
  $data = [];
  $data['msg'] = "";
  if (isset($_POST['login'])) {
    $email = $this->input->post('email');
      $password = $this->input->post('password');
      // validate fields
    $this->form_validation->set_rules('email', 'Email Id', 'trim|required',
    array(
        'required'=>'You must provide an %s')
      );
    $this->form_validation->set_rules('password', 'Password', 'trim|required',
    array(
      'required'=>'You must provide a %s')
    );
    if ($this->form_validation->run() == FALSE) {
      // validation not passed, so load the form again
        $this->load->view('login', $data);
      } 
    else {
        $result = $this->ModelCustomer->check_user($email, $password);
        if ($result) {
          $sess_array = [];
              $sess_array = [
                'email' => $result->email,
                'name' => $result->name,
              ];
              $this->session->set_userdata('login', $sess_array);
              redirect(base_url(),"refresh");
          
        }
        else {
          $msg = "Invalid login credentials";
          $data['msg'] = $msg;
          $this->load->view('login', $data);
        }
      }
    }
    else {
      $this->load->view('login', $data);
    }
  }  // end of function login

It sets session data for email and name using an array $sess_array[] and redirects the user to the home page.

Controller Method logout()

Method logout() deletes the session and redirects the user to home page. See below:


public function logout() {
		$this ->session ->sess_destroy();
		redirect(base_url(),"refresh");
	}

So, these were our controller methods, now let's see the Model methods in next step.

The Model (ModelCustomer.php)

The Customer Model has two methods, one for signup and the other for login. For signup, the model method name is signup(). This method takes the input data in an array and uses $db->insert() method to insert a row in the customer table. For login, you have seen, check_user() method is used. So now let's see the code for these methods in the model:

Model Method signup()


function signup($data) {
    if (!empty($data)) {
      $result = $this->db->insert('customer', $data);
      return $result;
    }
  }

Model Method check_user()


function check_user($email, $password) {
    $this->db->select('*');
    $this->db->from('customer');
    $this->db->where('email', $email);
    $this->db->where('password', md5($password));
    $this->db->limit(1);

    $query = $this->db->get();
    if ($query->num_rows() == 1) {
      return $query->row();
    }
    else {
      return FALSE;
    }
  }

Our views, controller and model are developed. Now we need to do some setup/configuration changes in CodeIgniter before we run the application. Let's do that in the next step.

Configuration files and Test the Application

We will update the below files in the config folder and we will also have our .htaccess file in the root directory. See below:

login in codeigniter with database

  1. Update autoload.php (application/config/autoload.php)

    We added 'database', 'session' and 'form_validation' in autoload libraries.

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

    Also, 'url' and 'form' are added in helper array.

    
    $autoload['helper'] = array('url','form');
    
  2. Update config file (application/config/config.php)

    Set 'base_url' and 'index_page' as below in this file:

    
    $config['base_url'] = 'http://localhost/customer/';
    
    
    $config['index_page'] = '';
    
  3. Update database setup file (application/config/database.php)

    As I mentioned before, I am using a database named 'demo' in localhost with user 'root', so I updated database.php as below:

    
    $active_group = 'default';
    $query_builder = TRUE;
    
    $db['default'] = array(
    	'dsn'	=> '',
    	'hostname' => 'localhost',
    	'username' => 'root',
    	'password' => '',
    	'database' => 'demo',
    	'dbdriver' => 'mysqli',
    	'dbprefix' => '',
    	'pconnect' => FALSE,
    	'db_debug' => (ENVIRONMENT !== 'production'),
    	'cache_on' => FALSE,
    	'cachedir' => '',
    	'char_set' => 'utf8',
    	'dbcollat' => 'utf8_general_ci',
    	'swap_pre' => '',
    	'encrypt' => FALSE,
    	'compress' => FALSE,
    	'stricton' => FALSE,
    	'failover' => array(),
    	'save_queries' => TRUE
    );
    
  4. Update routes file (application/config/routes.php) I updated routes.php for default controller which is customer. So, below code is for routes.php:
    
    $route['default_controller'] = 'CustomerController';
    $route['signup'] = 'CustomerController/signup';
    $route['logout'] = 'CustomerController/logout';
    $route['login'] = 'CustomerController/login';
    
    
    $route['404_override'] = '';
    $route['translate_uri_dashes'] = FALSE;
    

    Here I only updated default_controller as the customer, the rest in the file remain the same.

  5. Update .htaccess (hypertext access) file to remove index.php from the URL
    
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
    

    Using URL rewriting rule, it redirects all request except those which are not existing files or directories.

Test The Application

Make sure in your XAMPP control panel Apache server and MySQL services are running. Open the browser and run localhost/customer. You will see the home page displayed. Click on Signup and do a successful registration. Then using the email and password as given during registration, try to login. You should be able to login successfully and see the message displayed on the screen with the name and logout link. Also, test the validation for signup and login.

codeigniter 3 login pageNote: For simplicity, I have not enforced any password rule in the signup form. You should add at least some minimum requirement for password, maybe a minimum length can be given.

codeigniter 3 register formConclusion

Developing registration and login forms in CodeIgniter 3 can help you understand CodeIgniter 3 if you have just started working with it. Creating the views, writing Controller functions, form validations and database select-insert statements, quite a few areas you have to code for. This gives you a better understanding of how CodeIgniter 3 works.

Post a Comment

Save my Name and Email id for future comments