In this tutorial, we are going to learn about creating a unproblematic login form in CodeIgniter. In login grade, we fabricated registration module, login module and admin panel using sessions.



Nosotros also accept a paid gear up-to-use advance login & registration module congenital on CodeIgniter that you tin check out at CodeIgniter Login Registration Form.

Creating sessions in CodeIgniter is different from simple PHP. I will give you detailed information about all the method as we motility further in this tutorial.


Watch the live demo or download lawmaking from the link given below

codeigniter-login-form


Note : You lot can likewise refer thePHPProjectInstall.pdf file given in the download code binder.

Before starting, permit'southward have a wait on what we are going to acquire most.

  • Create login page, signup folio and admin folio.
  • Setting upward validation to all input field.
  • Cheque for existing users in database during signup process.
  • Check for username and password in database and testify their  information stored in database.
  • Create session for admin console, store users input information in session and destroy session(logout).

We are introducing a flow chart which volition give you a articulate vision about the objectives of this tutorial.

codeigniter-login-flow-chart

Firstly, set base URL in config.php file of CodeIgniter every bit given below:-

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

Tutorial Scripts in detail

Beneath are the details of the lawmaking used in this tutorial with proper explanation.

Database Tabular array: user_login

Now create a database name 'login' with a table 'user_login' using the code given beneath

            create database login; CREATE TABLE IF NOT EXISTS `user_login` ( `id` int(xi) Non NULL AUTO_INCREMENT, `user_name` varchar(255) Non NULL, `user_email` varchar(255) Non NULL, `user_password` varchar(255) Non NULL, Master KEY (`id`) )                      

Controller: user_authentication.php

Before beginning coding, let's load all the libraries required to make and manage login form.

First nosotros need to load session and validation libraries in controller file.

So, permit's start coding with controller. Create a file name 'user_authentication.php' in 'application/controllers' binder of CodeIgniter. Write the lawmaking given beneath in the file.

            <?php  session_start(); //we need to start session in order to access it through CI  Class User_Authentication extends CI_Controller {  public function __construct() { parent::__construct();  // Load class helper library $this->load->helper('form');  // Load form validation library $this->load->library('form_validation');  // Load session library $this->load->library('session');  // Load database $this->load->model('login_database'); }  // Evidence login page public function alphabetize() { $this->load->view('login_form'); }  // Bear witness registration page public office user_registration_show() { $this->load->view('registration_form'); }  // Validate and store registration information in database public part new_user_registration() {  // Bank check validation for user input in SignUp form $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); if ($this->form_validation->run() == Faux) { $this->load->view('registration_form'); } else { $data = array( 'user_name' => $this->input->mail('username'), 'user_email' => $this->input->mail service('email_value'), 'user_password' => $this->input->mail('countersign') ); $result = $this->login_database->registration_insert($data); if ($issue == True) { $data['message_display'] = 'Registration Successfully !'; $this->load->view('login_form', $data); } else { $data['message_display'] = 'Username already exist!'; $this->load->view('registration_form', $data); } } }  // Check for user login process public role user_login_process() {  $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');  if ($this->form_validation->run() == FALSE) { if(isset($this->session->userdata['logged_in'])){ $this->load->view('admin_page'); }else{ $this->load->view('login_form'); } } else { $data = assortment( 'username' => $this->input->post('username'), 'countersign' => $this->input->mail('countersign') ); $result = $this->login_database->login($data); if ($issue == Truthful) {  $username = $this->input->post('username'); $consequence = $this->login_database->read_user_information($username); if ($result != simulated) { $session_data = array( 'username' => $issue[0]->user_name, 'e-mail' => $result[0]->user_email, ); // Add user data in session $this->session->set_userdata('logged_in', $session_data); $this->load->view('admin_page'); } } else { $data = array( 'error_message' => 'Invalid Username or Password' ); $this->load->view('login_form', $data); } } }  // Logout from admin page public function logout() {  // Removing session data $sess_array = assortment( 'username' => '' ); $this->session->unset_userdata('logged_in', $sess_array); $data['message_display'] = 'Successfully Logout'; $this->load->view('login_form', $data); }  }  ?>          

Views: login_form.php

This will show login form on the view page.

            <html> <?php if (isset($this->session->userdata['logged_in'])) {  header("location: http://localhost/login/alphabetize.php/user_authentication/user_login_process"); } ?> <head> <title>Login Course</championship> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open up+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'> </caput> <body> <?php if (isset($logout_message)) { echo "<div form='message'>"; echo $logout_message; echo "</div>"; } ?> <?php if (isset($message_display)) { echo "<div class='bulletin'>"; echo $message_display; echo "</div>"; } ?> <div id="main"> <div id="login"> <h2>Login Course</h2> <hr/> <?php echo form_open('user_authentication/user_login_process'); ?> <?php echo "<div class='error_msg'>"; if (isset($error_message)) { echo $error_message; } echo validation_errors(); echo "</div>"; ?> <label>UserName :</characterization> <input type="text" proper name="username" id="proper noun" placeholder="username"/><br /><br /> <label>Password :</label> <input type="countersign" name="countersign" id="countersign" placeholder="**********"/><br/><br /> <input type="submit" value=" Login " proper noun="submit"/><br /> <a href="<?php repeat base_url() ?>index.php/user_authentication/user_registration_show">To SignUp Click Here</a> <?php echo form_close(); ?> </div> </div> </body> </html>          

Views: registration_form.php

This file will load to show signup grade.

            <html> <?php if (isset($this->session->userdata['logged_in'])) { header("location: http://localhost/login/index.php/user_authentication/user_login_process"); } ?> <head> <title>Registration Course</title> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'> </head> <trunk> <div id="main"> <div id="login"> <h2>Registration Form</h2> <60 minutes/> <?php repeat "<div class='error_msg'>"; echo validation_errors(); repeat "</div>"; repeat form_open('user_authentication/new_user_registration');  echo form_label('Create Username : '); echo"<br/>"; echo form_input('username'); echo "<div class='error_msg'>"; if (isset($message_display)) { echo $message_display; } repeat "</div>"; echo"<br/>"; echo form_label('Email : '); echo"<br/>"; $information = array( 'type' => 'electronic mail', 'name' => 'email_value' ); echo form_input($data); echo"<br/>"; echo"<br/>"; repeat form_label('Password : '); repeat"<br/>"; repeat form_password('password'); echo"<br/>"; echo"<br/>"; repeat form_submit('submit', 'Sign Up'); echo form_close(); ?> <a href="<?php echo base_url() ?> ">For Login Click Hither</a> </div> </div> </body> </html>          

Views: admin_page.php

This file load in the admin part, once user is successfully login to admin folio.

            <html> <?php if (isset($this->session->userdata['logged_in'])) { $username = ($this->session->userdata['logged_in']['username']); $email = ($this->session->userdata['logged_in']['email']); } else { header("location: login"); } ?> <head> <title>Admin Folio</championship> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' blazon='text/css'> </head> <trunk> <div id="profile"> <?php echo "Hello <b id='welcome'><i>" . $username . "</i> !</b>"; echo "<br/>"; echo "<br/>"; repeat "Welcome to Admin Page"; echo "<br/>"; repeat "<br/>"; echo "Your Username is " . $username; echo "<br/>"; repeat "Your Email is " . $email; echo "<br/>"; ?> <b id="logout"><a href="logout">Logout</a></b> </div> <br/> </body> </html>                      

Models : login_database.php

When a new user register.Information technology check for duplicate user registration.

            <?php  Class Login_Database extends CI_Model {  // Insert registration data in database public function registration_insert($data) {  // Query to bank check whether username already exist or not $condition = "user_name =" . "'" . $data['user_name'] . "'"; $this->db->select('*'); $this->db->from('user_login'); $this->db->where($status); $this->db->limit(i); $query = $this->db->get(); if ($query->num_rows() == 0) {  // Query to insert data in database $this->db->insert('user_login', $information); if ($this->db->affected_rows() > 0) { render truthful; } } else { return fake; } }  // Read data using username and password public function login($data) {  $status = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['countersign'] . "'"; $this->db->select('*'); $this->db->from('user_login'); $this->db->where($condition); $this->db->limit(1); $query = $this->db->get();  if ($query->num_rows() == 1) { return true; } else { return fake; } }  // Read information from database to show data in admin folio public part read_user_information($username) {  $status = "user_name =" . "'" . $username . "'"; $this->db->select('*'); $this->db->from('user_login'); $this->db->where($condition); $this->db->limit(i); $query = $this->db->get();  if ($query->num_rows() == 1) { return $query->result(); } else { return faux; } }  }  ?>          

CSS : manner.css

Blueprint for login, admin and registration page.

            #main{ width:960px; margin:50px automobile; font-family unit:raleway; }  span{ color:red; }  h2{ groundwork-color: #FEFFED; text-align:center; edge-radius: 10px 10px 0 0; margin: -10px -40px; padding: 30px; }  #login{  width:300px; float: left; border-radius: 10px; font-family:raleway; border: 2px solid #ccc; padding: 10px 40px 25px; margin-elevation: 70px; }  input[blazon=text],input[type=countersign], input[type=electronic mail]{ width:99.5%; padding: 10px; margin-superlative: 8px; border: 1px solid #ccc; padding-left: 5px; font-size: 16px; font-family unit:raleway; }  input[type=submit]{ width: 100%; background-colour:#FFBC00; colour: white; border: 2px solid #FFCB00; padding: 10px; font-size:20px; cursor:arrow; edge-radius: 5px; margin-lesser: 15px; }  #profile{ padding:50px; edge:1px dashed gray; font-size:20px; background-color:#DCE6F7; }  #logout{ bladder:correct; padding:5px; border:dashed 1px gray; margin-pinnacle: -168px; }  a{ text-ornament:none; color: cornflowerblue; }  i{ color: cornflowerblue; }  .error_msg{ color:cerise; font-size: 16px; }  .message{ position: absolute; font-weight: bold; font-size: 28px; color: #6495ED; left: 262px; width: 500px; text-align: center; }          

Process

Starting time of all information technology is needed to type  the given beneath URL in browser.

When browser get the above url it will display a login page. This page contains a login department and a signup link.

The whole procedure includes :-

  • SignUp procedure and
  • SignIn process

And so, permit'south learn about these processes.

Sign Up Process:

When yous click on singup link, information technology will redirect you to 'SignUp.php' and display a signup course.

After filling all input field when you click on submit button, all data travels to new_user_registration() function of controller. This function beginning check validation for each field.

If your information is empty or invalid then it will generate an fault message but, if all input field get proper data then it will connect you to database.

Before inserting data to database, it first check for username in database.

If given username is already available in database, a 'username already exits ! ' message volition be displayed but if username is not available in database then information technology will insert all the information in the database and display a 'SignUp Successfullly !' message.


Sign In Process:

After signup, you can login past giving a valid username and password. If invalid username  or password will be given and then a error message will be displayed.

Now permit'south accept a expect at the whole procedure of SignIn. When you enters username and password, the values are travelled to  user_login_process() function in controller where the validation for each field is checked.

When all input given are valid and so user_login_process()  role matches the  given username and  password with information stored in database.

If match doesn't found and so y'all will exist redirected to login page and an fault message will be displayed. But, if friction match found in database and then session will be created and user data will be inserted into session data.

Now, these data are send to admin page where all information along with logout choice will exist displayed. When you will click on logout then logout() function will be called and where session data will exist destroyed. After this, you will be redirect to login page for a new login.


Pabbly Form Builder


Determination :

Thanks for reading the complete post. Hope you take enjoyed reading this blog post and got the concept. You can share your views in the space provided below and make it touch with us.