Wednesday 16 August 2017

Display Online Users using PHP Mysql with Ajax Jquery

How to Show Live Online User using PHP with Ajax Jquery - 1





How to Show Live Online User using PHP with Ajax Jquery - 2



It is very important for any website to find out who are currently login into our syste or who are online. Because it will increase the value of website into another user who has online to system. This type of feature most we have seen in social media or forum site. So in this post we have discuss topic like display user information who are currently login into our website by using simple PHP Script Mysql database with Ajax JQuery. If you are using internet and you have already seen on many website in which we can seen the number of online users. So displaying online user details may create nice image on the new visitors of websites.

For create this type of feature there are following steps to create this type of feature.

1. Store User Login Information in table
2. Update Last Activity of Login user into his login information
3. Fetch Online User data from table

Store User Login Information in table


First when user has login into our system then we have to save his login information like his id, login time into our login details database. When login into our system by entering correct login details then after we have create one SESSION variable login id in which we have store the id of login details id based on this id we can update his last activity table column data with current time stamp.

Update Last Activity of Login user into his login information


After storing user login information in table and generate one unique login id and store into SESSION variable, so we can access this variable value into accros our system. So when user logged into system after this we will update current time stamp into his last activity table column into login details based on the unique value of login id get from SESSION variable. For update time stamp data on every three second we have use Ajax with JQuery. For update last activity data we have make one jquery function and in that function we have use Ajax request which send request to server for update login user last activity data and by using JQuery setInterval method we have called this function on every three seconds. So this way we have update login user last activity data with current time stamp data by using Ajax JQuer with PHP Sever script.

Fetch Online User data from table


Now We have already discuss how logged in user data insert into login details details table and how we have update that login used login details every three seconds, now we have move to master user login. This master user can view who is currently logged into our website. So for this we have make one jquery function and in this function we have use Ajax request which send request to PHP server script for fetch data from login details table and here we have condition like it fetch only that data whose last activity table column data is current time stamp data minus five second. That means it only fetch that user data whose last activity time stamp data less than of current time stamp minus five. So this query will return only that user data who currently online with our system or use our system. After fetching this data we have use setInterval() method, by using this method we have called this jquery function on every three second. So on every three second it will display live online user data on web page.

So this is simple system in which we have discuss topic like how to display online information by using PHP PDO with Ajax JQuery and Mysql.




Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO('mysql:host=localhost;dbname=testing2', 'root', '');
session_start();
?>


login.php



<?php
//login.php
include('database_connection.php');
if(isset($_SESSION["type"]))
{
 header("location: index.php");
}
$message = '';

if(isset($_POST["login"]))
{
 if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
 {
  $message = "<label>Both Fields are required</label>";
 }
 else
 {
  $query = "
  SELECT * FROM user_details 
  WHERE user_email = :user_email
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    'user_email' => $_POST["user_email"]
   )
  );
  $count = $statement->rowCount();
  if($count > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if(password_verify($_POST["user_password"], $row["user_password"]))
    {
     $insert_query = "
     INSERT INTO login_details (
      user_id, last_activity) VALUES (
      :user_id, :last_activity)
     ";
     $statement = $connect->prepare($insert_query);
     $statement->execute(
      array(
       'user_id'  => $row["user_id"],
       'last_activity' => date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')))
      )
     );
     $login_id = $connect->lastInsertId();
     if(!empty($login_id))
     {
      $_SESSION["type"] = $row["user_type"];
      $_SESSION["login_id"] = $login_id;
      header("location: index.php");
     }
    }
    else
    {
     $message = "<label>Wrong Password</label>";
    }
   }
  }
  else
  {
   $message = "<label>Wrong Email Address</labe>";
  }
 }
}


?>

<!DOCTYPE html>
<html>
 <head>
  <title>How Display Users Online using PHP with Ajax JQuery</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 />
  <div class="container">
   <h2 align="center">How Display Users Online using PHP with Ajax JQuery</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">Login</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>User Email</label>
       <input type="text" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="login" value="Login" class="btn btn-info" />
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>


index.php



<?php
//index.php
include('database_connection.php');

if(!isset($_SESSION["type"]))
{
 header("location: login.php");
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>How Display Users Online using PHP with Ajax JQuery</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 />
  <div class="container">
   <h2 align="center">How Display Users Online using PHP with Ajax JQuery</h2>
   <br />
   <div align="right">
    <a href="logout.php">Logout</a>
   </div>
   <br />
   <?php
   if($_SESSION["type"] =="user")
   {
    echo '<div align="center"><h2>Hi... Welcome User</h2></div>';
   }
   else
   {
   ?>
   <div class="panel panel-default">
    <div class="panel-heading">Online User Details</div>
    <div id="user_login_status" class="panel-body">

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

<script>
$(document).ready(function(){
<?php
if($_SESSION["type"] == "user")
{
?>
function update_user_activity()
{
 var action = 'update_time';
 $.ajax({
  url:"action.php",
  method:"POST",
  data:{action:action},
  success:function(data)
  {

  }
 });
}
setInterval(function(){ 
 update_user_activity();
}, 3000);


<?php
}
else
{
?>
fetch_user_login_data();
setInterval(function(){
 fetch_user_login_data();
}, 3000);
function fetch_user_login_data()
{
 var action = "fetch_data";
 $.ajax({
  url:"action.php",
  method:"POST",
  data:{action:action},
  success:function(data)
  {
   $('#user_login_status').html(data);
  }
 });
}
<?php
}
?>

});
</script>


action.php



<?php
//action.php
include('database_connection.php');
if(isset($_POST["action"]))
{
 if($_POST["action"] == "update_time")
 {
  $query = "
  UPDATE login_details 
  SET last_activity = :last_activity 
  WHERE login_details_id = :login_details_id
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    'last_activity'  => date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa'))),
    'login_details_id' => $_SESSION["login_id"]
   )
  );
 }
 if($_POST["action"] == "fetch_data")
 {
  $output = '';
  $query = "
  SELECT login_details.user_id, user_details.user_email, user_details.user_image FROM login_details 
  INNER JOIN user_details 
  ON user_details.user_id = login_details.user_id 
  WHERE last_activity > DATE_SUB(NOW(), INTERVAL 5 SECOND) 
  AND user_details.user_type = 'user'
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $count = $statement->rowCount();
  $output .= '
  <div class="table-responsive">
   <div align="right">
    '.$count.' Users Online
   </div>
   <table class="table table-bordered table-striped">
    <tr>
     <th>No.</th>
     <th>Email ID</th>
     <th>Image</th>
    </tr>
  ';

  $i = 0;
  foreach($result as $row)
  {
   $i = $i + 1;
   $output .= '
   <tr> 
    <td>'.$i.'</td>
    <td>'.$row["user_email"].'</td>
    <td><img src="images/'.$row["user_image"].'" class="img-thumbnail" width="50" /></td>
   </tr>
   ';
  }
  $output .= '</table></div>';
  echo $output;
 }
}



?>


logout.php



<?php
//logout.php
session_start();
session_destroy();
header("location:login.php");
?>


Database



--
-- Database: `testing2`
--

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

--
-- Table structure for table `login_details`
--

CREATE TABLE IF NOT EXISTS `login_details` (
  `login_details_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `last_activity` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `user_details`
--

CREATE TABLE IF NOT EXISTS `user_details` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(200) NOT NULL,
  `user_password` varchar(200) NOT NULL,
  `user_type` enum('master','user') NOT NULL,
  `user_image` varchar(150) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_details`
--

INSERT INTO `user_details` (`user_id`, `user_email`, `user_password`, `user_type`, `user_image`) VALUES
(1, 'john_smith@gmail.com', '$2y$10$cHpf3TzonURXDENRiRF0de1ycSfnM4NJ27sdwyUCf5L.sewDlkCBe', 'master', ''),
(2, 'dona_huber@gmail.com', '$2y$10$lcLYyNeK1adgzYcBplv45uuXHFuFyWYThnj3nB2SZ/LbQvtWSoGjO', 'user', 'dona_huber.jpg'),
(3, 'roy_hise@gmail.com', '$2y$10$XlyVI9an5B6rHW3SS9vQpesJssKJxzMQYPbSaR7dnpWjDI5fpxJSS', 'user', 'roy_hise.jpg'),
(4, 'peter_goad@gmail.com', '$2y$10$n1B.FdHNwufTkmzp/pNqc.EiwjB8quQ1tBCEC7nkaldI5pS.et04e', 'user', 'peter_goad.jpg'),
(5, 'sarah_thomas@gmail.com', '$2y$10$s57SErOPlgkIZf1lxzlX3.hMt8LSSKaYig5rusxghDm7LW8RtQc/W', 'user', 'sarah_thomas.jpg'),
(6, 'edna_william@gmail.com', '$2y$10$mfMXnH.TCmg5tlYRhqjxu.ILly8s9.qsLKOpyxgUl6h1fZt6x/B5C', 'user', 'edna_william.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `login_details`
--
ALTER TABLE `login_details`
  ADD PRIMARY KEY (`login_details_id`);

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `login_details`
--
ALTER TABLE `login_details`
  MODIFY `login_details_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user_details`
--
ALTER TABLE `user_details`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

50 comments:

  1. Sir, I followed all the steps but the master can't see the users, I logged in in 3 different browser but still can't update on the master page. help

    ReplyDelete
  2. i like this post... thanks you

    ReplyDelete
  3. Sir if I add a new row in table name user_details and then I open my login page it gives me alert message password is incoreect however its not. . .

    ReplyDelete
  4. sorry, what type of password you where using because i created a user and i couldnt login

    ReplyDelete
  5. how do you encrypt passwords in phpmyadmin?

    ReplyDelete
  6. Hello
    very good work
    but the script does not work.
    I am connected as a master, but no users displayed.

    ReplyDelete
  7. Hi, good day having a problem to this tutorial can't display the online users in master login, I checked 20 times in the video what are the errors but the codes are the same and I use PHP 7 and I don't know what are the errors. I loved your every tutorial you made and hopefully you help me to this problem. Thank you.

    ReplyDelete
  8. what is the password of john_smith@gmail.com
    Thank you in advance

    ReplyDelete
  9. Libera o projeto para download

    ReplyDelete

  10. libera o project para daownloa

    ReplyDelete
  11. Thanks so much for this tutorial, this is the best I had ever had. However, I am havinh issue with the code, when I run the code everything works perfectly except that, the logged in simple user did not update, that is, even after I logged out the simmple user on a different brower it still showed that logged out simple user as online. Please, help me, what did you thick might be the cause in the script/code?
    thanks so much, for your tutorial and your reply.

    ReplyDelete
  12. after login showing wrong password..please reply

    ReplyDelete
  13. Code is not working. .
    No data fetch from database for master user.

    ReplyDelete
  14. hello sir i really need the source code

    ReplyDelete
  15. The online users does not logout when uploaded in go daddy server. Plz help......thnks

    ReplyDelete
    Replies
    1. Same here, nothings appear. whats wrong with the code? code or browser? please help me sir. Thank you in advance, more power ! God Bless!

      Delete
    2. Check the database connection correctly with the database setting that go daddy provides , then check links in all pages ,

      Delete
  16. Great Video!.. I just want to know if user login first time then login time will insert in the table and if user login second time then it will insert again new login time. Right?. There is some issue with an update in every 5 seconds. It's updating all the last_activity time which is related to the id. If this is true then at the end of the day how can we identify the total number of hours user logged in? and how can we check the history of the user if we update the all the last_activity time?

    ReplyDelete
    Replies
    1. I found my solution. There was some issue with my where condition. Thanks

      Delete
    2. Same here, nothings appear. whats wrong with the code? code or browser? please help me sir. Thank you in advance, more power ! God Bless!

      Delete
  17. what are the passwords for login

    ReplyDelete
  18. the video tutorial is nice but has a robotic voice. so irrating

    ReplyDelete
  19. Why am I directed on a blank page after click on login button ?

    ReplyDelete
  20. where did you print massage?

    ReplyDelete
  21. how to insert image in database form register page , and where is source code of registration of user

    ReplyDelete
  22. how to insert image from register page to database, and where is register.php page ... please help me

    ReplyDelete
  23. Same here, nothings appear. whats wrong with the code? code or browser? please help me sir. Thank you in advance, more power ! God Bless!

    ReplyDelete
  24. You can create a special column to store each Id's last login. By doing that, at the end you will do a mathematical process to identify a time elapsed since last login up to when a particular user left your system

    ReplyDelete
  25. I want to add live visitor in my website how can i do that
    www.codepopular.com

    ReplyDelete
  26. what happens when some user directly closes browser/tab or turn off computer ? It is not that good

    ReplyDelete
  27. This tutorial is ok. The $_SESSION variables from the login.php page are not passed successfully to the index.php page. Therefore I have to block out the code that checks if isset( $_SESSION["type"] ). Otherwise it keeps returning me to the login.php page. This is not good. I spent a lot of time trying to figure out why this happens but I don't know. However when i block out the code then the list is generated of online users.

    ReplyDelete
  28. Hello,
    Please, and what will do if the user will not use logout button, but use the X button of the browser?
    Do you have some auto delete of the record of the logged in user?
    Thanks a lot for the answer.
    Honza

    ReplyDelete
  29. I'm trying to apply this into codeigniter framework, but the ajax calling action.php doesnt work.

    How to adapt it into codeigniter?
    Thanks

    ReplyDelete
  30. would you have the register php

    ReplyDelete
  31. Fatal error: Call to undefined function password_verify() in C:\xampp\htdocs\usersonline\login.php on line 34

    ReplyDelete
  32. Great tutorial. Could I get some help with this? My online users are not displaying when logged in as master user. I have tried in several browsers

    ReplyDelete
  33. Sir, I followed all the steps but the master can't see the users, I logged in in 3 different browser but still can't update on the master page. help

    ReplyDelete
  34. Hi..for those who's can't see the user online..maybe you're not given the your time zone. To me, I just add date_default_timezone_set('YOUR LOCATION'); in action.php file:

    step 1: Open action.php file
    step 2: just add date_default_timezone_set('YOUR LOCATION'); at line no 4
    Note: Please change the 'YOUR LOCATION' to your time zone. For me, as I in Kuala Lumpur, Malaysia - so I cahange itu to 'Asia/Kuala_Lumpur'

    Example as below:-

    <?php
    //action.php
    include('database_connection.php');
    date_default_timezone_set('Asia/Kuala_Lumpur');
    if(isset($_POST["action"]))

    ReplyDelete
  35. yes it works,,,after adding time set in action page...thank you

    ReplyDelete
  36. hallo..when I change the password and try to login - it say 'wrong password'. So, how to change the password form the default password?

    ReplyDelete