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:
Table of Contents
Seting Apache
Jika menggunakan web server apache2 ubah setingan: nano /etc/apache2/apache2.conf
<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride all Require all granted </Directory>
Restart apache2:
sudo /etc/init.d/apache2 restart
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', 'https://www.seosatu.com/contact', '$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:
- form_login.php
- form_register.php
- 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>
Download File
Ingin latihan langsung bisa download file jadi: login_CI3.zip
Panduan install:
- ubah setingan file: index.php // berfungsi debug jika ada yg error.
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
- Jangan lupa seting konfigurasi database.
- Jika aplikasi sudah Jalan, OK — Langsung Register buat akun baru.
Disclaimer
Sistem belum memiliki multi hak akses user
- Belum ada kode validasi block gagal login 3x
- Disarankan menambahkan reCaptcha Google
- Fitur Reset / Lupa Passowrds
- Kode bebas / gratis untuk dikembangkan !
__Semoga bermanfaat & selamat beajar!