Form Login dan Register Menggunakan Session PHP PDO

Kembal lagi bersama kami, kali ini kami akan share bagaimana Form Login  dan Register Menggunakan Session PHP PDO. Pada potingan sebelumnya kami telah membahas beberapa tutorial Php.



Yang pertama yang mesti kita lakukan adalah membuat databasenya terlebih dahulu. Buat databse dengan nama tblusers

 -- phpMyAdmin SQL Dump
-- version 4.8.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 29, 2018 at 07:00 PM
-- Server version: 10.1.32-MariaDB
-- PHP Version: 7.2.5

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


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `tblusers`
--

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

--
-- Table structure for table `tblusers`
--

CREATE TABLE `tblusers` (
  `id` int(11) NOT NULL,
  `FullName` varchar(120) DEFAULT NULL,
  `EmailId` varchar(100) DEFAULT NULL,
  `Password` varchar(100) DEFAULT NULL,
  `ContactNo` char(11) DEFAULT NULL,
  `RegDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tblusers`
--

INSERT INTO `tblusers` (`id`, `FullName`, `EmailId`, `Password`, `ContactNo`, `RegDate`) VALUES
(1, 'arman', 'arman@gmail.com', '21232f297a57a5a743894a0e4a801fc3', '081524737', '2018-07-29 16:46:27'),
(2, 'iwa', 'abi@gmail.com', '21232f297a57a5a743894a0e4a801fc3', '12345', '2018-07-29 16:59:52');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tblusers`
--
ALTER TABLE `tblusers`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tblusers`
--
ALTER TABLE `tblusers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
 

Yang kedua adalah membuat koneksi kedatabase, disini kami membuat file tersendiri untuk koneksi ke database dengan nama config.php Tujuannya adalah kita lebih muda membuat koneksi kefile lain dengan hanya memanggil file config.php

 <?php 
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','tblusers');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?> 

Yang ketiga adalah membuat form register sekaligus kita hubungkan langsung kedabasenya. Buat file dengan nama register.php

 <?php
//error_reporting(0);
session_start();
include('config.php');
error_reporting(0);
if(isset($_POST['signup']))
{
  $fname=$_POST['fullname'];
  $email=$_POST['emailid']; 
  $mobile=$_POST['mobileno'];
  $password=md5($_POST['password']); 
  $sql="INSERT INTO  tblusers(FullName,EmailId,ContactNo,Password) VALUES(:fname,:email,:mobile,:password)";
  $query = $dbh->prepare($sql);
  $query->bindParam(':fname',$fname,PDO::PARAM_STR);
  $query->bindParam(':email',$email,PDO::PARAM_STR);
  $query->bindParam(':mobile',$mobile,PDO::PARAM_STR);
  $query->bindParam(':password',$password,PDO::PARAM_STR);
  $query->execute();
  $lastInsertId = $dbh->lastInsertId();
  if($lastInsertId)
  {
    echo "<script>alert('Registration successfull. Now you can login');</script>";
  }
  else 
  {
    echo "<script>alert('Something went wrong. Please try again');</script>";
  }
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Login Register PDO</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
</head>
<body>
  <br /><br />
  <div class="container">
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="register.php">REGISTER</a>
      <a class="navbar-brand" href="index.php">LOGIN</a>
    </div>
  </div>
</nav>
<br />
<h2 align="center">Please Register</h2>
<br/>
<form method="post" name="signup" onSubmit="return valid();">
 <div class="form-group">
   <label>FULNAME</label>
   <input type="text" class="form-control" name="fullname" placeholder="Full Name*" required="required">
 </div>
 <div class="form-group">
   <label>MOBILE NO</label>
   <input type="text" class="form-control" name="mobileno" placeholder="Mobile Number*" maxlength="10" required="required">
 </div>
 <div class="form-group">
   <label>EMAIL</label>
   <input type="email" class="form-control" name="emailid" id="emailid" placeholder="Email Address*" required="required">
 </div>
 <div class="form-group">
   <label>ENTER PASSWORD</label>
   <input type="password" class="form-control" name="password" placeholder="Password*" required="required">
 </div>
 <div class="form-group">
   <label>CONFIRM PASSWORD</label>
   <input type="password" class="form-control" name="confirmpassword" placeholder="Confirm Password*" required="required">
 </div>
 <div class="form-group">
   <button class="btn btn-primary" type="submit" name="signup" id="submit">REGISTER</button>
 </div>
</form>
</div>
</body>
</html>
 

Yang keempat yang perlu kita buat adalah membuat form login, buat file baru dengan nama index.php

 <?php
session_start();
include('config.php');
error_reporting(0);
if(isset($_POST['login']))
{
  $email=$_POST['email'];
  $password=md5($_POST['password']);
  $sql ="SELECT EmailId,Password,FullName FROM tblusers WHERE EmailId=:email and Password=:password";
  $query= $dbh -> prepare($sql);
  $query-> bindParam(':email', $email, PDO::PARAM_STR);
  $query-> bindParam(':password', $password, PDO::PARAM_STR);
  $query-> execute();
  $results=$query->fetchAll(PDO::FETCH_OBJ);
  if($query->rowCount() > 0)
  {
    $_SESSION['login']=$_POST['email'];
    $_SESSION['fname']=$results->FullName;
    $currentpage=$_SERVER['REQUEST_URI'];
    echo "<script type='text/javascript'> document.location = 'dashbord.php'; </script>";
  } else{
    
    echo "<script>alert('Invalid Details');</script>";

  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Login Register PDO</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <br /><br />
  <div class="container">
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="register.php">REGISTER</a>
      <a class="navbar-brand" href="index.php">LOGIN</a>
    </div>
  </div>
</nav>
<br />
<h2 align="center">Please Login</h2>
<br />
<form method="post">
 <div class="form-group">
   <label>ENTER EMAIL</label>
   <input type="email" class="form-control" name="email" placeholder="Email address*">
 </div>
 <div class="form-group">
   <label>ENTER PASSWORD</label>
   <input type="password" class="form-control" name="password" placeholder="Password*">
 </div>
 <div class="form-group">
   <button class="btn btn-primary" type="submit" name="login">LOGIN</button>
 </div>
</form>
</div>
</body>
</html>
 

Yang kelima kita membuat form dashbord, buat file baru dengan nama dashbord.php

 <!DOCTYPE html>
<html>
<head>
  <title>Login Register PDO</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <br /><br />
  <div class="container">
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="dashbord.php">HOME</a>
      <a class="navbar-brand" href="logout.php">LOGOUT</a>
    </div>
  </div>
</nav>
<br />
<h2 align="center">WELCOME TO TUTORIALS SIMPLE LOGIN AND LOGOUT USING PHP PDO</h2>
<br />
</div>
</body>
</html>
 

Yang terakhir kita buat file baru dengan nama logout.php, bertujuan untuk mengeksekusi proses logout.

 <?php
session_start(); 
$_SESSION = array();
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 60*60,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
unset($_SESSION['login']);
session_destroy(); // destroy session
header("location:index.php"); 
?>

 
Jika kalian ingin melihat langsung hasilnya silahkan klik button demo dibawah ini. Kalian bisa mencoba sendiri.


Sekian share kali ini semoga apa yang kami share bermanfaat bagi anda, Kami juga tidak menjelaskan secara detail satu per satu kodingan di atas, karena kami sangat menginginkan partisipasi anda untuk menanyakan sesuatu hal yang kurang anda mengerti di kolom komentar.


close