Skip to content

Instantly share code, notes, and snippets.

@AkaashSaini
Created November 19, 2022 04:11
Show Gist options
  • Save AkaashSaini/6ad9ed02898ab01f4224e31127f5dd87 to your computer and use it in GitHub Desktop.
Save AkaashSaini/6ad9ed02898ab01f4224e31127f5dd87 to your computer and use it in GitHub Desktop.
show all online users PHP
Step: 1 Create table : online_users
CREATE TABLE `online_users` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'
)
Step:2 Create file : online_users.php
<?php
session_start();
$session = session_id();
$time = time();
$time_check = $time-300; //We Have Set Time 5 Minutes
$tbl_name = "online_users";
$conn = new mysqli("localhost","root","password","test");
// Check connection
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
exit();
}
$sql = "SELECT * FROM $tbl_name WHERE session='$session'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
//If count is 0 , then enter the values
if ($count == "0") {
$sql1 = "INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1 = mysqli_query($conn, $sql1);
} else {
$sql2 = "UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2 = mysqli_query($conn, $sql2);
}
$sql3 = "SELECT * FROM $tbl_name";
$result3 = mysqli_query($conn, $sql3);
$count_user_online = mysqli_num_rows($result3);
echo "<b>Users Online : </b> $count_user_online ";
// after 5 minutes, session will be deleted
$sql4 = "DELETE FROM $tbl_name WHERE time<$time_check";
$result4 = mysqli_query($conn, $sql4);
//To see the result run this script in multiple browser.
mysqli_close($conn);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment