Membuat Form Login – Tutorial CodeIgniter 3

Membuat Form Login CodeIgniter 3

Pada tulisan kali ini kita membuat form login untuk aplikasi CodeIgniter kita. Pertama kita siapkan dulu assets yang akan kita gunakan nanti. untuk kesempatan kali ini kita gunakan template SB Admin 2 dari startbootstrap. Kemudian buat folder baru beri nama assets dan di dalamnya buat sebuah subfolder baru dengan nama sbadmin2. Selanjutnya extract file zip yang sudah di-download dan pindahkan isi folder yang sudah di-extract tadi ke dalam folder sbadmin2, sehingga akan terlihat lebih kurang seperti iniassets sb admin 2

Selanjutnya markicod (mari kita coding).

Buat file v_register.php dalam application / views / auth /
Folder auth buat sendiri ya

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta name="description" content="">
	<meta name="author" content="">

	<title><?= $title . ' | Belajar CI3' ?></title>
	<link rel="shortcut icon" type="image/x-icon" href="<?= BASE_URL('assets/sbadmin2/img/undraw_rocket.svg') ?>">

	<!-- Custom fonts for this template-->
	<link href="<?= BASE_URL('assets/sbadmin2/vendor/fontawesome-free/css/all.min.css') ?>" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

	<!-- Custom styles for this template-->
	<link href="<?= BASE_URL('assets/sbadmin2/css/sb-admin-2.css') ?>" rel="stylesheet">
</head>

<body class="bg-gradient-primary">
	<div class="container">

		<div class="card o-hidden border-0 shadow-lg my-5">
			<div class="card-body p-0">
				<!-- Nested Row within Card Body -->
				<div class="row">
					<div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
					<div class="col-lg-7">
						<div class="p-5">
							<div class="text-center">
								<h1 class="h4 text-gray-900 mb-5">Buat Akun!</h1>
							</div>
							<form class="user" method="POST" action="<?= BASE_URL('auth/register') ?>">
								<div class="form-group">
									<input type="text" class="form-control form-control-user" id="fullname" name="fullname" value="<?= set_value('fullname') ?>" placeholder="Nama Lengkap" autocomplete="off">
									<?= form_error('fullname', '<small class="text-danger pl-3">', '</small>') ?>
								</div>
								<div class="form-group">
									<input type="text" class="form-control form-control-user" id="username" name="username" value="<?= set_value('username') ?>" placeholder="Username" autocomplete="off">
									<?= form_error('username', '<small class="text-danger pl-3">', '</small>') ?>
								</div>
								<div class="form-group">
									<input type="text" class="form-control form-control-user" id="email" name="email" value="<?= set_value('email') ?>" placeholder="Alamat Email" autocomplete="off">
									<?= form_error('email', '<small class="text-danger pl-3">', '</small>') ?>
								</div>
								<div class="form-group row">
									<div class="col-sm-6 mb-3 mb-sm-0">
										<input type="password" class="form-control form-control-user" id="password" name="password" placeholder="Password">
									</div>
									<div class="col-sm-6">
										<input type="password" class="form-control form-control-user" id="passwordconf" name="passwordconf" placeholder="Ulangi Password">
									</div>
									<?= form_error('password', '<div class="col-sm-12"><small class="text-danger pl-3">', '</small></div>') ?>
								</div>
								<button type="submit" class="btn btn-primary btn-user btn-block mb-5">
									Buat Akun
								</button>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>

	</div>

	<script src="<?= BASE_URL('assets/sbadmin2/vendor/jquery/jquery.min.js') ?>"></script>
	<script src="<?= BASE_URL('assets/sbadmin2/vendor/bootstrap/js/bootstrap.bundle.min.js') ?>"></script>

	<script src="<?= BASE_URL('assets/sbadmin2/vendor/jquery-easing/jquery.easing.min.js') ?>"></script>

	<script src="<?= BASE_URL('assets/sbadmin2/js/sb-admin-2.min.js') ?>"></script>

</body>

</html>

Buat file v_login.php dalam application / views / auth /
Folder auth buat sendiri ya

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta name="description" content="">
	<meta name="author" content="">

	<title><?= $title . ' | Belajar CI3' ?></title>
	<link rel="shortcut icon" type="image/x-icon" href="<?= BASE_URL('assets/sbadmin2/img/undraw_rocket.svg') ?>">

	<!-- Custom fonts for this template-->
	<link href="<?= BASE_URL('assets/sbadmin2/vendor/fontawesome-free/css/all.min.css') ?>" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

	<!-- Custom styles for this template-->
	<link href="<?= BASE_URL('assets/sbadmin2/css/sb-admin-2.css') ?>" rel="stylesheet">
</head>

<body class="bg-gradient-primary">

	<div class="container">

		<!-- Outer Row -->
		<div class="row justify-content-center">

			<div class="col-xl-10 col-lg-12 col-md-9">

				<div class="card o-hidden border-0 shadow-lg my-5">
					<div class="card-body p-0">
						<!-- Nested Row within Card Body -->
						<div class="row">
							<div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
							<div class="col-lg-6">
								<div class="p-5">
									<div class="text-center">
										<h1 class="h4 text-gray-900 mb-5">Silakan Login</h1>
									</div>
									<?= $this->session->flashdata('message'); ?>
									<?= form_open('auth/login', array('class' => 'user')) ?>
									<div class="form-group">
										<input type="text" class="form-control form-control-user text-center" id="username" name="username" value="<?= set_value('username') ?>" placeholder="Email / Username" autocomplete="off" autofocus>
										<?= form_error('username', '<small class="text-danger pl-3">', '</small>') ?>
									</div>
									<div class="form-group">
										<input type="password" class="form-control form-control-user text-center" id="password" name="password" placeholder="Password">
										<?= form_error('password', '<small class="text-danger pl-3">', '</small>') ?>
									</div>
									<button type="submit" class="btn btn-primary btn-user btn-block mb-5">
										Login
									</button>
									<?= form_close() ?>
									<hr>
									<div class="text-center">
										<a class="small" href="<?= BASE_URL() ?>">Beranda</a>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

			</div>

		</div>

	</div>

	<script src="<?= BASE_URL('assets/sbadmin2/vendor/jquery/jquery.min.js') ?>"></script>
	<script src="<?= BASE_URL('assets/sbadmin2/vendor/bootstrap/js/bootstrap.bundle.min.js') ?>"></script>

	<script src="<?= BASE_URL('assets/sbadmin2/vendor/jquery-easing/jquery.easing.min.js') ?>"></script>

	<script src="<?= BASE_URL('assets/sbadmin2/js/sb-admin-2.min.js') ?>"></script>

</body>

</html>

Buat file permission_helper.php dalam application / helpers/
File dalam helpers ini diakhiri dengan _helper.php ya

<?php if (!defined('BASEPATH')) exit('no direct script allowed');

if (!function_exists('has_login')) {
	function has_login()
	{
		$ci = get_instance();
		$username = $ci->session->userdata('username');

		$query = $ci->db->get_where('users', array('username' => $username, 'is_active' => '1'))->row_array();

		$hasLoginDecision = ($query) ? TRUE : FALSE;
		return $hasLoginDecision;
	}
}

if (!function_exists('kick_it_out')) {
	function kick_it_out($kick_message = 'Akses tidak diizinkan', $alertType = 'danger')
	{
		$ci = get_instance();
		$ci->session->unset_userdata('username');
		$ci->session->unset_userdata('email');

		$ci->session->set_flashdata('message', '<div class="alert alert-' . $alertType . '" role="alert">' . $kick_message . '.</div>');
		redirect('auth/login');
	}
}

Ubah file autoload.php dalam application / config /

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

$autoload['packages'] = array();
$autoload['libraries'] = array('session', 'form_validation', 'database');
$autoload['drivers'] = array();
$autoload['helper'] = array('url', 'security', 'permission');
$autoload['config'] = array();
$autoload['language'] = array();
$autoload['model'] = array();

Buat file Auth.php dalam application / controllers /
File dalam controllers ini gunakan awalan huruf besar ya

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

class Auth extends CI_Controller
{
	public function login()
	{
		if ($this->session->userdata('username')) {
			redirect('admin');
		}

		$this->form_validation->set_rules('username', 'Username', 'required|trim', [
			'required' => 'Username wajib diisi'
		]);
		$this->form_validation->set_rules('password', 'Password', 'required|trim', [
			'required' => 'Password wajib diisi'
		]);

		if ($this->form_validation->run() == false) {
			$data['title'] = 'Login Page';
			$this->load->view('auth/v_login', $data);
		} else {
			$this->_login();
		}
	}


	private function _login()
	{
		$username = $this->input->post('username');
		$password = $this->input->post('password');

		$this->db->from('users');
		$this->db->where('email', $username);
		$this->db->or_where('username', $username);
		$user = $this->db->get()->row_array();

		// jika user ada
		if ($user) {
			// jika user aktif
			if ($user['is_active'] == '1') {
				// cek password
				if (password_verify($password, $user['password'])) {
					$data = [
						'username' => $user['username'],
						'email' => $user['email']
					];

					$this->session->set_userdata($data);
					redirect('admin', 'refresh');
				} else {
					$this->session->set_flashdata('message', '<div class="alert alert-warning" role="alert">Periksa kembali Password Anda!</div>');
					redirect('auth/login');
				}
			} else {
				$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Username belum diaktifkan!</div>');
				redirect('auth/login');
			}
		} else {
			$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Username belum terdaftar!</div>');
			redirect('auth/login');
		}
	}

	public function register()
	{
		if ($this->session->userdata('username')) {
			redirect('admin');
		}

		$this->form_validation->set_rules('fullname', 'Fullname', 'required|trim|alpha_numeric_spaces', [
			'required' => 'Nama Lengakap wajib diisi'
		]);
		$this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[users.username]|alpha_numeric', [
			'required' => 'username wajib diisi',
			'is_unique' => 'Username sudah digunakan, silakan buat Username berbeda'
		]);
		$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]', [
			'required' => 'Email wajib diisi',
			'valid_email' => 'Isi Email dengan benar',
			'is_unique' => 'Email ini sudah terdaftar'
		]);
		$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[1]|matches[passwordconf]', [
			'required' => 'Password wajib diisi',
			'min_length' => 'Password minimal 8 karakter',
			'matches' => 'Ulangi Password dengan benar'
		]);
		$this->form_validation->set_rules('passwordconf', 'Password Confirmation', 'matches[password]');

		if ($this->form_validation->run() == false) {
			$data['title'] = 'Buat Akun';
			$this->load->view('auth/v_register', $data);
		} else {
			$data = [
				'username' => htmlspecialchars($this->input->post('username', true)),
				'email' => htmlspecialchars($this->input->post('email', true)),
				'fullname' => $this->input->post('fullname'),
				'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT)
			];

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

			$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Selamat! akun berhasil dibuat.</div>');
			redirect('auth/login');
		}
	}

	public function logout()
	{
		$this->session->unset_userdata('username');
		$this->session->unset_userdata('email');

		$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Logout berhasil.</div>');
		redirect('auth/login');
	}
}

Buat file Admin.php dalam application / controllers /
Ingat: file dalam controllers ini menggunakan awalan huruf besar

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

class Admin extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		if (!has_login()) kick_it_out('Halaman yang Anda tuju hanya tersedia untuk pengguna yang sudah login');
		else $this->user = $this->db->get_where('users', ['username' => $this->session->userdata('username')])->row_array();
	}

	public function index()
	{
		echo "Hai " . $this->user['fullname'] . "<br><br>";
        echo "<a href=" . BASE_URL('auth/logout') . ">LOGOUT</a>";
	}
}

Sekarang akses di browser halaman localhost/belajar_ci3/auth/register setelah itu isi form pendaftaran lalu buat akun. Kemudian setelah itu akses phpMyAdmin dan ubah nilai is_active pada tabel users menjadi 1 agar user tersebut diizinkan untuk login

ganti nilai is active

Sekarang silakan login menggunakan username dan password yang telah didaftarkan tadi

About the Author

Assalamualaikum. Saya Ahmad Mazlan, Programmer muda yang masih belajar dan ingin segera berbagi tentang dunia programming. Siapa pun bisa membuat program, yang mereka butuhkan hanya belajar. Semua bisa menjadi Programmer selama memiliki keinginan yang kuat untuk belajar.

Tinggalkan Balasan