Whats the easiest way to determine if a user is online? (PHP/MYSQL)

前端 未结 10 1236
轻奢々
轻奢々 2020-12-02 05:24

Is there a way I can piggy back sessions to know if the user is online?

I.e: use logs on, I set a $_SESSION variable, user times out- cookie Garbage collector update

10条回答
  •  情歌与酒
    2020-12-02 05:52

    Here's a way on how to get the difference between two dates from a database in minutes, then check for the difference and set the online/offline status.

    $query = 'SELECT * FROM Users';
    $result = mysqli_query($mysqli, $query);
    
    foreach($result as $user){
        // date from the database
        $dbLastActivity = date("d-m-Y h:i:s a", strtotime($user['lastOnline']));
        // date now
        $now = date("d-m-Y h:i:s a", $date);
    
        // calculate the difference
        $difference = strtotime($now) - strtotime($dbLastActivity);
        $difference_in_minutes = $difference / 60;
    
        // check if difference is greater than five minutes
        if($difference_in_minutes < 5){
            // set online status
            $updateStatus = 'UPDATE Users SET Status="online" WHERE lastOnline="'.$user['lastOnline'].'"';
        } else {
            // set offline status
            $updateStatus = 'UPDATE Users SET Status="offline" WHERE lastOnline="'.$user['lastOnline'].'"';
        }
    
        // check if mysqli query was successful
        if (!$mysqli->query($updateStatus)){
            printf("Error Message %s\n", $mysqli->error);
        }
    } 
    

提交回复
热议问题