Cara Mengambil Ip User, Waktu Login, Waktu Logout dan Status Login Menggunakan PHP MySql

//lh4.googleusercontent.com/-eAXyxy2JJKA/AAAAAAAAAAI/AAAAAAAAGS4/OHgzqHzCvtQ/s512-c/photo.jpg
September 14, 2018




Selamat malam kembali lagi bersama kami kali ini kami akan share bagaimana membuat cara mengambil atau Mengetahui Ip User, Waktu Login, Waktu Logout dan Status Login Menggunakan PHP MySql, kemudian dimasukkan kedalam database.

Tujuannya dari tutorial di atas adalah untuk mengetahui aktivitas user dalam menggunakan sistem yang ada. Tujuan utamanya adalah sebagai security sistem.

Langsung saja yang pertama yang mesti kita lakukan adalah membuat databsenya, byat databse dengan nama ipuser kemudian masukkan tabel database dibawah ini.

 -- phpMyAdmin SQL Dump
-- version 4.8.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 14, 2018 at 05:51 AM
-- 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: `ipuser`
--

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

--
-- Table structure for table `userlog`
--

CREATE TABLE `userlog` (
  `id` int(11) NOT NULL,
  `uid` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `userip` binary(16) NOT NULL,
  `loginTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `logout` varchar(25) NOT NULL,
  `status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `fullName` varchar(50) DEFAULT NULL,
  `userEmail` varchar(50) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `idUser` varchar(20) DEFAULT NULL,
  `regDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updationDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  `status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `fullName`, `userEmail`, `password`, `idUser`, `regDate`, `updationDate`, `status`) VALUES
(1, 'Armaan', 'arman@gmail.com', 'ee11cbb19052e40b07aac0ca060c23ee', '12345', '2018-03-06 04:26:14', '2018-04-05 10:36:14', 1);

--
-- Indexes for dumped tables
--

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

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `userlog`
--
ALTER TABLE `userlog`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=258;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
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 */;
 

Kedua buat buat file dengan nama config.php fungsinya adalah koneksi  kedatabase.

 <?php
define('DB_HOST', 'localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'ipuser');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?> 

Ketiga buat file dengan nama index.php fungsi file adalah sebgaai form login, dan terdapat beberapa fungsi. Misalnya fungsi memanggil username dan password dan memasukkan data ip, waktu login dan logout dan tentunya status login sukses atau tidak.

 <?php session_start();
error_reporting(0);
include("include/config.php");
if(isset($_POST['submit'])) {
  $_SESSION['submit']='';
}
if(isset($_POST['submit']))
{

  $ret=mysqli_query($con,"SELECT * FROM users WHERE userEmail='".$_POST['username']."' and password='".md5($_POST['password'])."'");
  $num=mysqli_fetch_array($ret);
  if($num>0)
  {
$extra="dashbord.php";//
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$num['id'];
$host=$_SERVER['HTTP_HOST'];
$uip=$_SERVER['REMOTE_ADDR'];
$status=1;
$log=mysqli_query($con,"insert into userlog(uid,username,userip,status) values('".$_SESSION['id']."','".$_SESSION['login']."','$uip','$status')");
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
else
{
  $_SESSION['login']=$_POST['username'];  
  $uip=$_SERVER['REMOTE_ADDR'];
  $status=0;
  mysqli_query($con,"insert into userlog(username,userip,status) values('".$_SESSION['login']."','$uip','$status')");
  $errormsg="Invalid username or password";
  $extra="login.php";
}
}

?>
<!DOCTYPE html>
<html>
<head>
  <link rel="shortcut icon" href="images/profile.gif">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Main CSS-->
  <link rel="stylesheet" type="text/css" href="login/css/main.css">
  <!-- Font-icon css-->
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <title>Example</title>
  <script type="text/javascript">
    function valid()
    {
      if(document.forgot.password.value!= document.forgot.confirmpassword.value)
      {
        alert("Password and Confirm Password Field do not match  !!");
        document.forgot.confirmpassword.focus();
        return false;
      }
      return true;
    }
  </script>
</head>
<body>
  <section class="material-half-bg">
    <div class="cover">
    </div>
    
  </section>
  <section class="login-content">
    <div class="login-box">
     <p style="padding-left:20%; color:red">
      <?php if($errormsg){
        echo htmlentities($errormsg);
      }?>
    </p>
    <p style="padding-left:20%;  color:green">
      <?php if($msg){
        echo htmlentities($msg);
      }?></p>
      
      <form class="login-form" method="post">
        <a class="brand" href="../index.html">
          <div class="thumbnail"><center><img src="images/profile.gif" height="100"/></center></div></a><p/>
          <div class="form-group">
            <input class="form-control" name="username" type="text" placeholder="Email" autofocus>
          </div>
          <div class="form-group">
            <input class="form-control" type="password" name="password" placeholder="Password">
          </div>

          <div class="form-group btn-container">
            <button type="submit" name="submit" class="btn btn-primary btn-block"><i class="fa fa-sign-in fa-lg fa-fw"></i>SIGN IN</button>
          </div>
        </form>
      </div>
    </section>
    <!-- Essential javascripts for application to work-->
    <script src="login/js/jquery-3.2.1.min.js"></script>
    <script src="login/js/popper.min.js"></script>
    <script src="login/js/bootstrap.min.js"></script>
    <script src="login/js/main.js"></script>
    <!-- The javascript plugin to display page loading on top-->
    <script src="login/js/plugins/pace.min.js"></script>
  </body>
  </html> 



Keempat buat file dengan nama dashbord.php fungsi dari file ini adalah untuk form yang dituju ketika user berhasil login, dan juga sebagai form hostory login. Pada file dibawah juga terdapat fungsi deleted history.

 <?php session_start();
include('include/config.php');
if(strlen($_SESSION['login'])==0)
{ 
  header('location:index.php');
}
else{
date_default_timezone_set('Asia/Jakarta');// change according timezone
$currentTime = date( 'd-m-Y h:i:s A', time () );

if(isset($_GET['del']))
{
  mysqli_query($con,"delete from userlog where id = '".$_GET['id']."'");
  $_SESSION['delmsg']="User Logs deleted !!";
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>example</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>
  
  <!--Script CSS-->
  <link type="text/css" href='https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css' rel='stylesheet'>
  <link type="text/css" href='https://cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.css' rel='stylesheet'>
  <link type="text/css" href='https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css' rel='stylesheet'>
  
</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="logout.php">Logout !!</a>
    </div>
  </div>
</nav>
<br />
<!--h2 align="center">EXPORT FILE</h2-->
<br />

<div class="form-group">

 <?php if(isset($_GET['del']))
  {?>
    <div class="alert alert-danger">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <strong>Oh snap!</strong>   <?php echo htmlentities($_SESSION['delmsg']);?><?php echo htmlentities($_SESSION['delmsg']="");?>
    </div>
  <?php } ?>

  <table id="example" class="display responsive nowrap" style="width:100%">
    <thead>
      <tr>
        <th>No</th>
        <th>User Email</th>
        <th>User IP </th>
        <th>Login Time</th>
        <th>Logout Time </th>
        <th>Status </th>
        <th>Action </th>
      </tr>
    </thead>
    <tbody>

      <?php $query=mysqli_query($con,"select * from userlog");
      $cnt=1;
      while($row=mysqli_fetch_array($query))
      {
        ?>                  

        <tr>

         <td><?php echo htmlentities($cnt);?></td>
         <td><?php echo htmlentities($row['username']);?></td>
         <td><?php echo htmlentities($row['userip']);?></td>
         <td> <?php echo htmlentities($row['loginTime']);?></td>
         <td><?php echo htmlentities($row['logout']); ?></td>
         <td><?php $st=$row['status'];

         if($st==1)
         {
          echo "Successfull";
        }
        else
        {
          echo "Failed";
        }
        ?></td>
        <td>
         <a href="dashbord.php?id=<?php echo $row['id']?>&del=delete" onClick="return confirm('Are you sure you want to delete?')"><button type="button" class="btn btn-danger">Delete</button></a>
       </td> 
     </tr>

     <?php $cnt=$cnt+1; } ?>                           

   </table>
   
   
 </div>

 <!--Script Javascript-->
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
 <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
 <script src="https://cdn.datatables.net/responsive/2.2.1/js/dataTables.responsive.min.js"></script>
 <script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
 <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.colVis.min.js"></script>
 
 <script>
   $(document).ready(function() {
    $('#example').DataTable( {
      dom: 'Bfrtip',
      buttons: [
      'colvis'
      ]
    } );
  } );
</script>

</body>
</html>
<?php } ?> 



Terakhir buat file dengan nama logout.php file ini menyimpan fungsi logout.

 <?php session_start();
include("include/config.php");
$_SESSION['login']=="";
date_default_timezone_set('Asia/Jakarta');
$ldate=date( 'Y-m-d H:i:s', time () );
mysqli_query($con,"UPDATE userlog  SET logout = '$ldate' WHERE username = '".$_SESSION['login']."' ORDER BY id DESC LIMIT 1");
session_unset();
$_SESSION['errmsg']="You have successfully logout";
?>
<script language="javascript">
 document.location="index.php";
</script> 

Jika teman-teman ingin melihat demonya langsung silahkan klik button demo, kalian juga bisa mendowloadnya langsung.

DEMO                             DOWNLOAD

Email : arman@gmail.com
password : user

Sekian share kali ini semoga apa yang kami share bermanfaat bagi anda, jika kalian masih ada yang belum paham silahkan tinggalkan komentar dan mulai berdiskusi dengan kami.


Related Post

SUBSCRIBE TO OUR NEWSLETTER

closed