PHP

User login and login tracking using PHP

In this tutorial I will explain  user login system and how to track user accesslog.  In user log we can see how to track user ip and user login and logout  time.

Files Included for this system

config.php
index.php
welcome.php
userlog.php
logout.php
Create a Database with name demos. Demos database contain two tables :
login
userlog
Structure of the login table

CREATE TABLE `login` (
  `id` int(11) NOT NULL,
  `userName` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Structure of userlog table

CREATE TABLE `userlog` (
  `id` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `userIp` varbinary(16) NOT NULL,
  `loginTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Database Connection (config.php)
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'demos');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Now create an HTML form with two fields username and password

<form name="login" method="post" >
  <header>Login</header>
  <p style="color:red;"><?php echo $_SESSION['msg'];?><?php echo $_SESSION['msg']="";?></p>
  <label>Username <span>*</span></label>
  <input name="username" type="text" value="" required />
  <label>Password <span>*</span></label>
  <input name="password" type="password" value="" required />
  <button type="submit" name="login">Login</button>
</form>

Create PHP script for user login and login tacking put this script above the index.php page.

<?php
session_start();
include 'config.php';
if(isset($_POST['login']))
{
$username=$_POST['username']; // Get username
$password=$_POST['password']; // get password
//query for match the user inputs
$ret=mysqli_query($con,"SELECT * FROM login WHERE userName='$username' and password='$password'");
$num=mysqli_fetch_array($ret);
// if user inputs match if condition will runn
if($num>0)
{
$_SESSION['login']=$username; // hold the user name in session
$_SESSION['id']=$num['id']; // hold the user id in session
$uip=$_SERVER['REMOTE_ADDR']; // get the user ip
$action="Login";// query for inser user log in to data base
mysqli_query($con,"insert into userlog(userId,username,userIp,action) values('".$_SESSION['id']."','".$_SESSION['login']."','$uip','$action')")
// code redirect the page after login
$extra="welcome.php";
$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
// If the userinput no matched with database else condition will run
else
{
$_SESSION['msg']="Invalid username or password";
$extra="index.php";
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
 }
}
?>

Here the full code of index.php

<?php
session_start();
include 'config.php';
if(isset($_POST['login']))
{
$username=$_POST['username']; // Get username
$password=$_POST['password']; // get password
//query for match the user inputs
$ret=mysqli_query($con,"SELECT * FROM login WHERE userName='$username' and password='$password'");
$num=mysqli_fetch_array($ret);
// if user inputs match if condition will runn
if($num>0)
{
$_SESSION['login']=$username; // hold the user name in session
$_SESSION['id']=$num['id']; // hold the user id in session
$uip=$_SERVER['REMOTE_ADDR']; // get the user ip
$action="Login";// query for inser user log in to data base
mysqli_query($con,"insert into userlog(userId,username,userIp,action) values('".$_SESSION['id']."','".$_SESSION['login']."','$uip','$action')")
// code redirect the page after login
$extra="welcome.php";
$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
// If the userinput no matched with database else condition will run
else
{
$_SESSION['msg']="Invalid username or password";
$extra="index.php";
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
 }
}
?>
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>User login and tracking in PHP using PHP OOPs Concept</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form name="login" method="post" >
  <header>Login</header>
  <p style="color:red;"><?php echo $_SESSION['msg'];?><?php echo $_SESSION['msg']="";?></p>
  <label>Username <span>*</span></label>
  <input name="username" type="text" value="" required />
  <label>Password <span>*</span></label>
  <input name="password" type="password" value="" required />
  <button type="submit" name="login">Login</button>
</form>
</body>
</html>

After login, you will redirect to welcome.php

<?php
session_start();
if($_SESSION['login'])
{
?><!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body bgcolor="#d6c2c2">
<p>Welcome : <?php echo $_SESSION['login'];?> | <a href="logout.php">Logout</a> </p>
<p><a href="userlog.php">User Access log</a></p>
 </body>
</html>
<?php
} else{
header('location:logout.php');
}
?>

After login, you can see your login details by click on User Access log(userlog.php)

<?php
session_start();
include('config.php');
if($_SESSION['login'])
{
?><!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body bgcolor="#d6c2c2">
<p><a href="welcome.php">Welcome : <?php echo $_SESSION['login'];?> </a>| <a href="logout.php">Logout</a> </p>
<table align="center" border="1">
<tr>
<th>Sno.</th>
<th>User Id</th>
<th>User Name</th>
<th>User Ip</th>
<th>Action Performed</th>
<th>Login Time</th>
</tr>
<?php $query=mysqli_query($con,"select * from userLog where userId='".$_SESSION['id']."'");
$cnt=1;
while($row=mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo $cnt;?></td>
<td><?php echo $row['userId'];?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo $row['userIp'];?></td>
<td><?php echo $row['action'];?></td>
<td><?php echo $row['actionTime'];?></td>
</tr>
<?php $cnt=$cnt+1;
} ?>
</table>
</body>
</html>
<?php
} else{
header('location:logout.php');
}
?>

Logout script (logout.php)

<?php
session_start();
include('config.php');
// Getting logout time in db
$username=$_SESSION['login']; // hold the user name in session
$uid=$_SESSION['id']; // hold the user id in session
$uip=$_SERVER['REMOTE_ADDR']; // get the user ip
$action="Logout";
// query for inser user log in to data base
$query=mysqli_query($con,"insert into userlog(userId,username,userIp,action) values('$uid','$username','$uip','$action')");
if($query){
session_unset();
//session_destroy();
}
$_SESSION['msg']="You have logged out successfully..!";
?>
<script language="javascript">
document.location="index.php";
</script>

CSS (style.css)

html, body {
  border: 0;
  padding: 0;
  margin: 0;
  height: 100%;
}
body {
  background: tomato;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
}
form {
  background: white;
  width: 40%;
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7);
  font-family: lato;
  position: relative;
  color: #333;
  border-radius: 10px;
}
form header {
  background: #FF3838;
  padding: 30px 20px;
  color: white;
  font-size: 1.2em;
  font-weight: 600;
  border-radius: 10px 10px 0 0;
}
form label {
  margin-left: 20px;
  display: inline-block;
  margin-top: 30px;
  margin-bottom: 5px;
  position: relative;
}
form label span {
  color: #FF3838;
  font-size: 2em;
  position: absolute;
  left: 2.3em;
  top: -10px;
}
form input {
  display: block;
  width: 78%;
  margin-left: 20px;
  padding: 5px 20px;
  font-size: 1em;
  border-radius: 3px;
  outline: none;
  border: 1px solid #ccc;
}
form .help {
  margin-left: 20px;
  font-size: 0.8em;
  color: #777;
}
form button {
  position: relative;
  margin-top: 30px;
  margin-bottom: 30px;
  left: 50%;
  transform: translate(-50%, 0);
  font-family: inherit;
  color: white;
  background: #FF3838;
  outline: none;
  border: none;
  padding: 5px 15px;
  font-size: 1.3em;
  font-weight: 400;
  border-radius: 3px;
  box-shadow: 0px 0px 10px rgba(51, 51, 51, 0.4);
  cursor: pointer;
  transition: all 0.15s ease-in-out;
}
form button:hover {
  background: #ff5252;
}
View Demo
Download Source Code(User login and login tracking using PHP)
Size: 4.57 KB
Version: V 2.0

Recommended Tutorials for you


Tags

Anuj kumar

This is Anuj Kumar. I’m a professional web developer with 5+ years of experience. I write blogs in my free time. I love to learn new technologies and share with others. I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials. .

23 Comments

  1. I have been searching for a tutorial like this for some time so thanks. However I have got the code to work up to when I click on user access log. Tt shows the heading but no the data, also link to code shows a 404 error

      1. Thanks Anuj the download now works great! I notice you mentioned in an earlier reply that a time logged out version was also available, but this download does not include the time logged out info. Also is it possible to amend the code to also capture pages visited information? Thanks again for a great tutorial.
        Regards
        Alan

  2. I downloaded the file, but everytime i use the Demo’s login and passowrd(anuj/Demo@123) it says “Invalid Username and Password” where can i locate the registered accounts? Thanks

  3. I want to track windows system information using php. Like RAM size, HDD size, OS, Computer name, processor, ip address, Mac address logged in user , monitors details, keyboard , mouse details,
    If any code related my query so please help me.
    Thanks in advance.

  4. Hi Anuj kumar,
    I need logout time like login time. can you please let me know how we get
    I will be thankful to you for this
    Kind Regards

  5. i have used your code in my application in local host it was working but when i uploaded in my hosting server data in not inserting in the userlogs table i have check the the connection is proper
    table is blank any help will be appreciated .

  6. i have used your code in my application in local host it was working but when i uploaded in my hosting server data in not inserting in the userlogs table i have check the the connection is proper
    table is blank any help will be appreciated .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top button
Close
Close