Sistem Login, Register CodeIgniter 3 (Secured Hash) + Bootstrap

275 Shares

Cara Membuat sistem login, Register Akun di Codeigniter dengan Enkripsi Password Hash di jamin aman / Secured + tema Bootstrap

Password_hash adalah salah satu fungsi yang dimiliki PHP untuk melakukan hashing menggunakan algoritma satu arah (one-way hashing). Fungsi ini terdapat pada PHP versi 7.0 ke atas & Update: Versi Codeigniter yang digunakan adalah: 3.xx

Algoritma untuk melakukan hash yaitu menggunakan BCRYPT dan akan menghasilkan output sepanjang 60 karakter. Secara konsep login codeigniter akan menerapkan menerapkan fungsi PHP:

password_hash() dan password_verify()

Pada tutorial ini admin akan share belajar sistem login aman (secure) sederhana dengan framework codeigniter + template bootstrap 4, untuk ujicoba latiahan menggunakan xampp (localhost)  & database mysql / phpmyadmin.

» Informasi panduan codeigniter + Bootstrap:

Baca:  Memasang Template Dinamis Bootstrap 4 di CodeIgniter

 

Buat database (Mysql)

Silahkan buat database baru dengan nama: login > tabel: user

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

CREATE TABLE `user` (
  `id` int(8) NOT NULL,
  `nama` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  `password` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`id`, `nama`, `email`, `password`) VALUES
(30, 'admin', 'seo.satu1@gmail.com', '$2y$05$45XlEAS82O77pwBBTcdDguWYZHkwDcvH4lcxHYrzkMg9cBV8zyDIu'),
(31, 'seosatu', 'admin@seosatu.com', '$2y$05$Og8T8VFcZJYyTJ7L5xTPG.DOSZ75OTfMmhydFyNDgR7uKSCV4gtsK'),
(32, 'seosatu', 'cloudflare@amiklan.com', '$2y$05$o5xTBd3DfVlqM2brDfG1j.TUfMcQlz7XUEpwuEhjQaMj3Yz6gSkzK');


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


ALTER TABLE `user`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
COMMIT;

 

Membuat Fitur Login Codeigniter 3

buat folder baru > xampp > hddocs > latihanCI

  • URL: http://localhost/latihanCI

Koneksi Database + Codeigniter: application/config/database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
  'dsn'	=> '',
  'hostname' => 'localhost',
  'username' => 'root',
  'password' => '',
  'database' => 'login',
  '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
);

 

Seting Routes: application/config/routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$route['default_controller'] = 'user';
$route['404_override'] = '';
$route['translate_uri_dashes'] = TRUE;

Buat File Helper login Hash

sistem login hash dengan membuat custome helper, folder: application/helper: login_helper.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

if(!function_exists('get_hash'))
{
    
    function get_hash($PlainPassword)
    {

    	$option=[
                'cost'=>5,// proses hash sebanyak: 2^5 = 32x
    	        ];
    	return password_hash($PlainPassword, PASSWORD_DEFAULT, $option);

   }
}

if(!function_exists('hash_verified'))
{
    
    function hash_verified($PlainPassword,$HashPassword)
    {

    	return password_verify($PlainPassword,$HashPassword) ? true : false;

   }
}

 

Seting autoload: application/config/autoload.php

$autoload['libraries'] = array('session', 'database', 'form_validation','template');
$autoload['helper'] = array('url','form','login');

 

Kode Controllers

Metode susunan folder / kode login codeigniter menggunakan MVC: User.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

         public function __construct() {
   	     parent::__construct();
   	     $this->load->model('m_user');
         }

  public function index(){
        
        if($this->session->userdata('is_login')==TRUE)
          {
          redirect('user/securepage','refresh');
          }

    $this->template->load('role','user/form_login');
    
  }

  public function register() {

    if($this->session->userdata('is_login')==TRUE)
          {
          redirect('user/securepage','refresh');
          }

    $this->template->load('role','user/form_register');
    
  }

  public function register_proses(){

  $this->form_validation->set_rules('nama', 'Nama', 'trim|required|min_length[3]|max_length[22]');
  $this->form_validation->set_rules('email', 'E-mail', 'trim|required|min_length[3]|max_length[45]|is_unique[user.email]');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[12]');

  if ($this->form_validation->run() == TRUE ) {

       if($this->m_user->m_register()){
           
           $this->session->set_flashdata('pesan', 'Register berhasil, silahkan  Sign In.');
           redirect('/','refresh');

       }else{

           $this->session->set_flashdata('pesan', 'Register user gagal!');
           redirect('/','refresh');

       }

  } else {
    
    $this->template->load('role','user/form_register');
  }

  
    
  }

  public function login_proses() {

  $this->form_validation->set_rules('email', 'E-mail', 'trim|required|min_length[3]|max_length[45]');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[12]');

    if ($this->form_validation->run() == TRUE) {
    	
          if($this->m_user->m_cek_mail()->num_rows()==1) {
          
             $db=$this->m_user->m_cek_mail()->row();
             if(hash_verified($this->input->post('password'),$db->password)) {

                     $data_login=array('is_login'=>TRUE,
                             'email'  =>$db->email,
                             'nama'   =>$db->nama);
             
                     $this->session->set_userdata($data_login);
                     redirect('user/securepage','refresh');

                        } else {

                        $this->session->set_flashdata('pesan', 'Login gagal: password salah!');
                        redirect('/','refresh');

                        }

          } else { // jika email tidak terdaftar!
           
           $this->session->set_flashdata('pesan', 'Login gagal: email salah!');
           redirect('/','refresh');

          }

    } else { 

    	$this->template->load('role','user/form_login');
    }

  }


  public function securepage() {

    if($this->session->userdata('is_login')==FALSE)
          {
          redirect('/','refresh');
          }

        $this->template->load('role','user/securepage');

  }


  public function logout() {

    $this->session->unset_userdata('is_login');
    $this->session->unset_userdata('nama');
    $this->session->unset_userdata('email');

    session_destroy();
    //$this->session->set_flashdata('pesan', 'Sign Out Berhasil!');
    redirect('/','refresh');
  }

}

/* End of file User.php */
/* Location: ./application/controllers/User.php */

Kode: function login, register, securepage & logout.

 

Ket. kode controllers

public function __construct() {
   	     parent::__construct();
   	     $this->load->model('m_user');
         }

Note: include / loading class model: m_user.php

 

public function index(){
        
        if($this->session->userdata('is_login')==TRUE)
          {
          redirect('user/securepage','refresh');
          }

    $this->template->load('role','user/form_login');
    
  }

  public function register() {

    if($this->session->userdata('is_login')==TRUE)
          {
          redirect('user/securepage','refresh');
          }

    $this->template->load('role','user/form_register');
    
  }

Note: home index, buka form register & seting hak akses halaman user dengan session login.

 

public function register_proses(){

  $this->form_validation->set_rules('nama', 'Nama', 'trim|required|min_length[3]|max_length[22]');
  $this->form_validation->set_rules('email', 'E-mail', 'trim|required|min_length[3]|max_length[45]|is_unique[user.email]');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[12]');

  if ($this->form_validation->run() == TRUE ) {

       if($this->m_user->m_register()){
           
           $this->session->set_flashdata('pesan', 'Register berhasil, silahkan  Sign In.');
           redirect('/','refresh');

       }else{

           $this->session->set_flashdata('pesan', 'Register user gagal!');
           redirect('/','refresh');

       }

  } else {
    
    $this->template->load('role','user/form_register');
  }

  
    
  }

note: proses register user & validasi form.

 

public function login_proses() {

  $this->form_validation->set_rules('email', 'E-mail', 'trim|required|min_length[3]|max_length[45]');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[12]');

    if ($this->form_validation->run() == TRUE) {
    	
          if($this->m_user->m_cek_mail()->num_rows()==1) {
          
             $db=$this->m_user->m_cek_mail()->row();
             if(hash_verified($this->input->post('password'),$db->password)) {

                     $data_login=array('is_login'=>TRUE,
                             'email'  =>$db->email,
                             'nama'   =>$db->nama);
             
                     $this->session->set_userdata($data_login);
                     redirect('user/securepage','refresh');

                        } else {

                        $this->session->set_flashdata('pesan', 'Login gagal: password salah!');
                        redirect('/','refresh');

                        }

          } else { // jika email tidak terdaftar!
           
           $this->session->set_flashdata('pesan', 'Login gagal: email salah!');
           redirect('/','refresh');

          }

    } else { 

    	$this->template->load('role','user/form_login');
    }

  }

Note: proses login user dengan metode hash, session user & enkripsi password.

 

public function securepage() {

    if($this->session->userdata('is_login')==FALSE)
          {
          redirect('/','refresh');
          }

        $this->template->load('role','user/securepage');

  }

Note: halaman securepage jika telah berhasil login.

 

public function logout() {

    $this->session->unset_userdata('is_login');
    $this->session->unset_userdata('nama');
    $this->session->unset_userdata('email');

    session_destroy();
    //$this->session->set_flashdata('pesan', 'Sign Out Berhasil!');
    redirect('/','refresh');
  }

Note: kode untuk logout user.

 

Models

File codeigniter login: M_user.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class M_user extends CI_Model {


  public function m_register() {

        $data = array('nama' =>$this->input->post('nama'),
                      'email'=>$this->input->post('email'),
                      'password'=>get_hash($this->input->post('password')));

        return $this->db->insert('user',$data);

  }

     public function m_cek_mail() {

     return $this->db->get_where('user',array('email' => $this->input->post('email')));

     }	

}

/* End of file M_user.php */
/* Location: ./application/models/M_user.php */

Note: kode input data register & cek email saat user login.

 

File Kode Views

Buat folder baru “user”, selanjutnya buat file kode codeigniter login:

  1. form_login.php
  2. form_register.php
  3. securepage.php

 

Kode form_login.php

  <div class="col-md-4">

        <h2 class="my-4">Login
          <small>user</small>
        </h2>

  <font color="green"><?php echo $this->session->flashdata('pesan'); ?></font>
  <?php echo form_open('user/login_proses',''); ?>
  <div class="form-group">
    <label for="exampleInputEmail1">e-mail</label>
    <input type="email" name="email"class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
    <?php echo form_error('email', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" name="password" class="form-control" id="exampleInputPassword1">
    <?php echo form_error('password', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <button type="submit" class="btn btn-primary">Sign In</button>
<?php echo form_close(); ?>
<br>
<p>
Buat akun baru: <?php echo anchor('user/register', 'Register!', 'attributes'); ?>
</p>
</div>

 

Kode form_register.php

  <div class="col-md-4">

        <h2 class="my-4">Register
          <small>user</small>
        </h2>

  <font color="green"><?php echo $this->session->flashdata('pesan'); ?></font>
  <?php echo form_open('user/register-proses',''); ?>

  <div class="form-group">
    <label for="exampleInputEmail1">Nama</label>
    <input type="text" name="nama"class="form-control" id="exampleInputEmail1">
    <?php echo form_error('nama', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputEmail1">e-mail</label>
    <input type="email" name="email"class="form-control" id="exampleInputEmail1">
    <?php echo form_error('email', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" name="password" class="form-control">
    <?php echo form_error('password', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <button type="submit" class="btn btn-primary">Register Now!</button>
<?php echo form_close(); ?>
</div>

 

Kode securepage.php

<div class="col-md-8">

      <h2 class="my-4">Login
        <small>berhasil</small>
      </h2>

      <p>
      	Selamat datang: <b><?php echo $this->session->userdata('nama');  ?></b>,<br>

      	Ini adalah halaman user / member area yang telah di amankan oleh sistem login hash & session login.
      </p>

       Keluar halaman: <?php echo anchor('user/logout', 'Sign Out', 'attributes'); ?>

</div>

 

Preview Login

ket. halaman login CI

ket. halaman register user

ket. halaman securepage setalah user berhasil login.

 

Disclaimer Sistem login CI belum ada fitur remember me, lupa password

  1. Sistem belum memiliki multi hak akses user
  2. Belum ada kode validasi block gagal login 3x
  3. Disarankan menambahkan reCaptcha Google
  4. Fitur Reset / Lupa Passowrds
  5. Kode bebas / gratis untuk dikembangkan !

 

Download file Login Codeigniter 

Mengalami error / kesulitan saat belajar kita telah sediakan file CI 3 yang sudah jadi tingggal pakai & bisa di unduh secara gratis untuk latihan belajar: latihanLoginCI.zip

__Semoga bermanfaat & selamat beajar!

Editor: | Update: Oktober 22, 2020

Baca Juga:

4 thoughts on “Sistem Login, Register CodeIgniter 3 (Secured Hash) + Bootstrap

  1. Avatar for husnihusni

    Unable to load the requested class: Template

    di autoload [‘libraries’] sudah aku panggil

    Reply
    1. Avatar for Tn. AndreasTn. Andreas Admin

      download dan gunakan file latihan , biar tidak error.

  2. Avatar for RifaiRifai

    Kalo buat supaya saat user gagal login lebih dari 3x diblokir gimana gan…?

    Reply
    1. Avatar for Tn. AndreasTn. Andreas

      silahkan buat field baru tabel user – database untuk hitung proses gagal login, gunakan data : numer dan field status blokir: char (yes / no)

      Indikasi gagal login karena salah password 3x dan email tetap sama, sehingga patokan data bedasarkan email untuk primary key nya.
      —-
      masukan kode kode input pada pada function login gagal, masukan dalam data tadi, nanti buat fungsi IF, jika user akan login & gagal ambil data jika > dari 3x maka status diblokir.

      Jika user berhasil login maka delete data proses login sehingga akan menjadi 0.

      itu konsep nya, kedepan akan saya buatkan materi lengkap + kode.

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *