how can i show user online or offline from its session in php,mysql and ajax

21,300

Solution 1

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.

Solution 2

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.

Share:
21,300
Hafiz Usman aftab
Author by

Hafiz Usman aftab

Updated on July 09, 2022

Comments

  • Hafiz Usman aftab
    Hafiz Usman aftab almost 2 years

    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