membuat Validasi Login di PHP dan MySQL

Validasi Login di PHP dan MySQL

Membuat Validasi Login di PHP dan MySQL
Kali ini saya akan bahas terkait validasi login di PHP dan MySQL, tentunya anda sudah mengetahui bahwa validasi diperlukan untuk memverifikasi login dari user yang terdaftar di database, jadi ketika ada user yang tidak memiliki privilage tentunya tidak bisa masuk kedalam system karena ketika divalidasi  user tersebut belum terdaftar dan tidak ada didatabse user.

nah untuk membuat validasi interaktif dan informatif seperti gambar di atas anda bisa memulainya dengan membuat database dengan nama latihan kemudian silahkan anda dumping sql code berikut ini, silahkan anda copy dan pastekan di tab SQL pada database admin phpmyadmin.



-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 04, 2020 at 03:23 AM
-- Server version: 10.1.19-MariaDB
-- PHP Version: 5.5.38

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `invoice`
--

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `user_id` int(10) NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` text NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `nama_usaha` varchar(100) NOT NULL,
  `alamat` varchar(250) NOT NULL,
  `kota` varchar(50) NOT NULL,
  `telp` varchar(20) NOT NULL,
  `no_hp` varchar(14) NOT NULL,
  `level` enum('user','ppic','admin','acc') NOT NULL,
  `gambar` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

INSERT INTO `user` (`user_id`, `username`, `password`, `fullname`, `email`, `nama_usaha`, `alamat`, `kota`, `telp`, `no_hp`, `level`, `gambar`) VALUES
(8, 'hakko', 'c59df3cca6af0550c9612b2319773f98fed4a5ad', 'Hakko Bio Richard', '[email protected]', 'PT. NiqoWeb Cikarang', 'Kab. Bekasi 17530', 'Cikarang', '085694984803', '085694984803', 'admin', '../admin/gambar_admin/hakkoblogs.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `user_id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;

selanjutnya buatlah sebuah folder dengan nama latihan di drive c:/xampp/htdocs/ kemudian silahkan anda copy dan pastekan kode berikut ini dengan nama conn.php

<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "latihan";

$koneksi = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

if(mysqli_connect_errno()){
    echo 'Gagal melakukan koneksi ke Database : '.mysqli_connect_error();
}   
?>

langkah selanjutnya adalah membuat form login, untuk mempermudah anda, silahkan anda copy dan pastekan kode berikut ini kemudian simpan dengan  nama index.php di drive c:/xampp/htdocs/latihan

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Login Aplikasi Invoicing www.hakkoblogs.com</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="dist/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="dist/css/ionicons.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="plugins/iCheck/square/blue.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body class="hold-transition" background="dist/img/2.jpg">
    <div class="login-box">
      <div class="login-logo">
        <a href="#" style="color: white;"> <!-- <span class="glyphicon glyphicon-qrcode"></span> --> Aplikasi Invoice</a>
      </div><!-- /.login-logo -->
      <div class="login-box-body">
      <!--<center><img src="#" height="50" width="300" /></center>-->
         <p class="login-box-msg"><?php if (isset($_GET['error'])) {echo 
                  "<div class='alert alert-danger alert-gradient alert-dismissible fade in' role='alert'>
                            <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>x</span></button>
                            <strong>Error!</strong> $_GET[error]
                          </div>";} else { echo "";} ?></p>
        <form action="proseslogin.php" id="login" name="login" method="post">
          <div class="form-group has-feedback">
            <input type="text" id="username" name="username" class="form-control" autocomplete="off" placeholder="Username" required="required">
            <span class="glyphicon glyphicon-user form-control-feedback"></span>
          </div>
          <div class="form-group has-feedback">
            <input type="password" id="password" name="password" class="form-control" autocomplete="off" placeholder="Password" required="password">
            <span class="glyphicon glyphicon-lock form-control-feedback"></span>
          </div>
          <div class="row">
            <div class="col-xs-12">
              <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
            </div><!-- /.col -->
          </div>
        </form>

        <center><h5 class="form-signin">Copyright &copy; <a href="#" data-toggle="modal" data-target="#contact">www.hakkoblogs.com</a> 2018</h5></center> 

      </div><!-- /.login-box-body -->
    </div><!-- /.login-box -->

    
     <!-- Modal Dialog Contact -->
 <div class="modal fade" id="contact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Contact Us</h4>
      </div>
      <div class="modal-body">
      Aplikasi Invoicing ini dibuat oleh
       Hakko Bio Richard yang dapat dihubungi di :
      <table>
      <tr>
      <td>No Telepon</td> <td>:</td> <td>0856 949 848 03</td>
      </tr>
      <br />
      <tr>
      <td>E-mail</td><td>:</td> <td><a href="mailto:[email protected]">[email protected]</a> | <a href="mailto:[email protected]">[email protected]</a></td>
      </tr> 
      <br />
      <tr>
      <td>Blog</td>       <td>:</td> <td><a href="http://www.hakkoblogs.com" target="_blank">www.hakkoblogs.com</a></td>
      </tr>
      <br />
      <tr>
      <td>Website</td>    <td>:</td> <td><a href="http://www.niqoweb.com" target="_blank">www.niqoweb.com</a></td>
      </tr>
       </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- end dialog modal -->

    <!-- jQuery 2.1.4 -->
    <script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
    <!-- Bootstrap 3.3.5 -->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <!-- iCheck -->
    <script src="plugins/iCheck/icheck.min.js"></script>
    <script>
      $(function () {
        $('input').iCheck({
          checkboxClass: 'icheckbox_square-blue',
          radioClass: 'iradio_square-blue',
          increaseArea: '20%' // optional
        });
      });
    </script>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Login Aplikasi Invoicing www.hakkoblogs.com</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="dist/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="dist/css/ionicons.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="plugins/iCheck/square/blue.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body class="hold-transition" background="dist/img/2.jpg">
    <div class="login-box">
      <div class="login-logo">
        <a href="#" style="color: white;"> <!-- <span class="glyphicon glyphicon-qrcode"></span> --> Aplikasi Invoice</a>
      </div><!-- /.login-logo -->
      <div class="login-box-body">
      <!--<center><img src="#" height="50" width="300" /></center>-->
         <p class="login-box-msg"><?php if (isset($_GET['error'])) {echo 
                  "<div class='alert alert-danger alert-gradient alert-dismissible fade in' role='alert'>
                            <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>x</span></button>
                            <strong>Error!</strong> $_GET[error]
                          </div>";} else { echo "";} ?></p>
        <form action="proseslogin.php" id="login" name="login" method="post">
          <div class="form-group has-feedback">
            <input type="text" id="username" name="username" class="form-control" autocomplete="off" placeholder="Username" required="required">
            <span class="glyphicon glyphicon-user form-control-feedback"></span>
          </div>
          <div class="form-group has-feedback">
            <input type="password" id="password" name="password" class="form-control" autocomplete="off" placeholder="Password" required="password">
            <span class="glyphicon glyphicon-lock form-control-feedback"></span>
          </div>
          <div class="row">
            <div class="col-xs-12">
              <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
            </div><!-- /.col -->
          </div>
        </form>

        <center><h5 class="form-signin">Copyright &copy; <a href="#" data-toggle="modal" data-target="#contact">www.hakkoblogs.com</a> 2018</h5></center> 

      </div><!-- /.login-box-body -->
    </div><!-- /.login-box -->

    
     <!-- Modal Dialog Contact -->
 <div class="modal fade" id="contact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Contact Us</h4>
      </div>
      <div class="modal-body">
      Aplikasi Invoicing ini dibuat oleh
       Hakko Bio Richard yang dapat dihubungi di :
      <table>
      <tr>
      <td>No Telepon</td> <td>:</td> <td>0856 949 848 03</td>
      </tr>
      <br />
      <tr>
      <td>E-mail</td><td>:</td> <td><a href="mailto:[email protected]">[email protected]</a> | <a href="mailto:[email protected]">[email protected]</a></td>
      </tr> 
      <br />
      <tr>
      <td>Blog</td>       <td>:</td> <td><a href="http://www.hakkoblogs.com" target="_blank">www.hakkoblogs.com</a></td>
      </tr>
      <br />
      <tr>
      <td>Website</td>    <td>:</td> <td><a href="http://www.niqoweb.com" target="_blank">www.niqoweb.com</a></td>
      </tr>
       </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- end dialog modal -->

    <!-- jQuery 2.1.4 -->
    <script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
    <!-- Bootstrap 3.3.5 -->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <!-- iCheck -->
    <script src="plugins/iCheck/icheck.min.js"></script>
    <script>
      $(function () {
        $('input').iCheck({
          checkboxClass: 'icheckbox_square-blue',
          radioClass: 'iradio_square-blue',
          increaseArea: '20%' // optional
        });
      });
    </script>
  </body>
</html>

langkah selanjutnya adalah membuat file verifikasi login, silahkan anda copy dan pastekan kode berikut ini kemudian simpan dengan nama proseslogin.php di direktori c:/xampp/htdocs/latihan

<?php
include ("conn.php");
date_default_timezone_set('Asia/Jakarta');

session_start();

$username = $_POST['username'];
$password1 = $_POST['password'];
$password = sha1($password1);

//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);

if (empty($username) && empty($password)) {
    header('location:index.php?error=Username dan Password Kosong!');
} else if (empty($username)) {
    header('location:index.php?error=Username Kosong!');
} else if (empty($password)) {
    header('location:index.php?error=Password Kosong!');
}

$q = mysqli_query($koneksi, "select * from user where username='$username' and password='$password'");
$row = mysqli_fetch_array ($q);

if (mysqli_num_rows($q) == 1) {
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['username'] = $username;
    $_SESSION['fullname'] = $row['fullname'];
    $_SESSION['email'] = $row['email'];
    $_SESSION['nama_usaha'] = $row['nama_usaha'];
    $_SESSION['alamat'] = $row['alamat'];
    $_SESSION['kota'] = $row['kota'];
    $_SESSION['telp'] = $row['telp'];
    $_SESSION['gambar'] = $row['gambar'];    
    $_SESSION['level']  = $row['level'];
    
    if ($_SESSION['level'] == 'admin'){
        header('location:admin/index.php');
    } /**else if ($_SESSION['level'] == 'superuser'){
        header('location:superuser/index.php');
    } else if ($_SESSION['level'] == 'user'){
        header('location:user/penjualan.php');
    }**/
    
} else {
    header('location:index.php?error=Anda Belum Terdaftar!');
}
?>

jalankan Aplikasi di browser, silahkan anda akses aplikasi validasi login tersebut di browser dengan mengetikan localhost/latihan, jika berhasil maka anda akan mendapatkan tampilan seperti gambar di atas.

Penjelasan singkat kode

Kalau anda perhatikan ketika form login di submit maka file proseslogin.php memverifikasi login dengan mengeceknya terlebih dahulu seperti  kode di bawah ini

if (empty($username) && empty($password)) {
    header('location:index.php?error=Username dan Password Kosong!');
} else if (empty($username)) {
    header('location:index.php?error=Username Kosong!');
} else if (empty($password)) {
    header('location:index.php?error=Password Kosong!');
}

jika ternyata form terisi oleh inputan maka akan dilanjutkan dengan pengecekan data ke database melalui query berikut

$q = mysqli_query($koneksi, "select * from user where username='$username' and password='$password'");
$row = mysqli_fetch_array ($q);

if (mysqli_num_rows($q) == 1) {
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['username'] = $username;
    $_SESSION['fullname'] = $row['fullname'];
    $_SESSION['email'] = $row['email'];
    $_SESSION['nama_usaha'] = $row['nama_usaha'];
    $_SESSION['alamat'] = $row['alamat'];
    $_SESSION['kota'] = $row['kota'];
    $_SESSION['telp'] = $row['telp'];
    $_SESSION['gambar'] = $row['gambar'];    
    $_SESSION['level']  = $row['level'];
    
    if ($_SESSION['level'] == 'admin'){
        header('location:admin/index.php');
    } /**else if ($_SESSION['level'] == 'superuser'){
        header('location:superuser/index.php');
    } else if ($_SESSION['level'] == 'user'){
        header('location:user/penjualan.php');
    }**/
    
} else {
    header('location:index.php?error=Anda Belum Terdaftar!');
}

kemudian jika di cek data tidak ada maka pesan error muncul di form login secara otomatis menggunakan method get, seperti pada potongan kode berikut di file index.php

<p class="login-box-msg"><?php if (isset($_GET['error'])) {echo 
                  "<div class='alert alert-danger alert-gradient alert-dismissible fade in' role='alert'>
                            <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>x</span></button>
                            <strong>Error!</strong> $_GET[error]
                          </div>";} else { echo "";} ?></p>


dari kode tersebut terlihat variabel error yang di ambil dengan method get dari file proseslogin.php

nah bagaimana? cukup mudah bukan untuk membuat validasi login di PHP dan MySQL? pastinya ya, semoga tutorial singkat ini bisa bermanfaat dan penjelasan kode yang saya paparkan bisa anda mengerti dengan mudah, silahkan anda coba dan anda praktekkan, karena tanpa mencoba dan tanpa praktek anda tidak akan mendapatkan hasil.

Happy Coding & Programming

0 Response to "membuat Validasi Login di PHP dan MySQL"

Post a Comment

Berkomentar dengan bijak dan sopan.

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel