2

please tell me way how can i show user is online or offline by accessing its session. this is php and mysql query

header('Content-Type: application/json');
$array = array();

$res = mysql_query("SELECT * FROM `posts` WHERE status=1");
if(mysql_num_rows($res) > 0){
    while($row = mysql_fetch_assoc($res)){  
        $array[] = $row['user_id'];  // this adds each online user id to the array         
    }
}
echo json_encode($array);

i try this code this is js file

<script type="text/javascript">    
   $(document).ready(function() {                               
     setInterval(function(){
      $.ajax({
           url: 'status.php',
           dataType: "json",
           type: 'GET',
           success: function(data) {
               if (data.length > 0){  // if at least 1 is online
                  $('.status').each(function(){  // loop through each of the user posts
                      var userid = parseInt($(this).attr('id').replace('user','')); // get just the userid #
                      if($.inArray(userid, data) !== -1){  // if userid # in the returned data array set to online
                           $(this).css({background: 'green'});  
                      } else{  // else if userid # not in the returned data array set to offline
                           $(this).css({background: 'grey'});  
                      }
                  });
               } 
               else { // if no one is online, set all to offline
                   $('.status').css({background: 'grey'});
               }

           }
        });
    }, 2000); //2s just for testing. Set to 15s when code fully works.
   });
 </script>

but this code is not run according to my requerements it according to what i save in DB every time i save my status in DB then on the behave of this it give me result. what i want

  1. when user close its browser then logically its session is destroy then i want to show its status offline

2.if user maintain his session then its status is online

Lalit Kumar B
  • 47,486
  • 13
  • 97
  • 124
Hafiz Usman aftab
  • 300
  • 2
  • 5
  • 15

5 Answers5

6

There is no straight forward to do this afaik. There is no proper way to detect whether a user has closed his browser. One method I have seen commonly used to solve this specific problem [within your context] is by using a last_activity_timestamp field in the posts table. Each time a user does any activity, the last_activity_timestamp is updated with the new time.

$res = mysql_query("UPDATE `posts` SET last_update_timestamp = NOW() WHERE user_id = {$currentUserId};");

Then in your code for checking whether a user is currently online, you can also check whether a certain time period (say 20 minutes) has elapsed since the last activity of a user like so:

$res = mysql_query("SELECT * FROM `posts` WHERE status=1 AND TIMESTAMPDIFF(MINUTE, last_activity_timestamp, NOW()) > 20;");

If the last activity of a user was more than 20 minutes old, then he is effectively logged out.

fijas
  • 1,272
  • 1
  • 16
  • 26
  • But what if the user just reads a few posts and not doing any acitvity? – Amal Ts Apr 16 '15 at 06:02
  • @AmalSurendran that really depends on the kind of site you have. For example, you can check if the user was inactive for 15 minutes and then show an "Away" status. After 30 minutes if the user is still inactive you can show "Offline" status. Or maybe, another way is you can set a timer in javascript and notify the user that he is about to be logged off and that he has to click a button to stay logged in. These are issues that can be solved on the business side of the logic... – fijas Apr 16 '15 at 06:18
3

PHP stores session data for each user in a temporary folder on the server. This folder is defined in the php.ini configuration file under the variable session.save_path. Locate this value from within your php.ini file, or alternatively, create a php file with:

<?php echo "Session Save Path: " . ini_get( 'session.save_path');?>

as it's contents, and open the file in your browser.

Once you find the save path for the session data, open up that folder and you'll notice a fairly simple structure. All sessions are stored in the format: sess_$SESSIONID .

Session data is serialized before being stored on disk. As such, objects stored in the session file would have to be deserialized before being usable. However, if you're using plain text, which is stored as-is, to store your session data (ex. $_SESSION['userid'] = 1234) to store information about your users, it should be easy enough to parse out the data you're looking for from within the files. That would be an alternative for you to get the active sessions and set the status online.

Amal Ts
  • 857
  • 1
  • 6
  • 28
  • but when session destroy it will work to show status offline ?? – Hafiz Usman aftab Apr 15 '15 at 05:59
  • When the session destroys, the entry wont be available in the file. The the same way you poll the table, poll the file and update the status. – Amal Ts Apr 16 '15 at 06:03
  • This looks like a solid solution. Can you give more details about deserialise the info from the sessions file to display on a page? – Carlos27 Feb 11 '19 at 14:16
0

You could/should use UNIX timestamps.

This User online offline status - offline status issue can better display user is online or offline.

if($time >= $loggedtime)
Community
  • 1
  • 1
Rinku
  • 1,175
  • 1
  • 12
  • 13
0

I wrote up a little peice of code that works like a charm for me to update user's status's with online and offline.

All you have to do is call these 2 lines in every page, (I use a function in my main user page and call that in the header then call the header in every page)

    mysqli_query($con, "UPDATE users SET status = 'offline' WHERE TIMESTAMPDIFF(MINUTE, lastactive, NOW()) > 1 AND username = '$username' LIMIT 1");
    mysqli_query($con, "UPDATE users SET status = 'online' WHERE TIMESTAMPDIFF(MINUTE, lastactive, NOW()) < 1 AND username = '$username' LIMIT 1");
Ben Za
  • 21
  • 1
  • 9
0

simple step, just call page using javascript like this

<!DOCTYPE html>
<html>
<head>
    <title>Autorefresh Browser using jquery</title>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            startRefresh();
        });
        function startRefresh() {
            setTimeout(startRefresh,2000);
            $.get('text.html', function(data) {
                $('#viewHere').html(data);
            });
        }
    </script>

</head>
<body>
    <div id="viewHere"></div>
</body>
</html>

change text.html with your page and setTimeout(startRefresh,2000); value as your want.

sorry for my bad english

this is full source

https://www.youtube.com/watch?v=Q907KyXcFHc