Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDaniphord Mwajah
186 PointsHow to get accurate guest and online visitors number on you website with PHP code?
I am trying to add a section where visitors of the website can be counted and displayed according to their status, whether online or just visiting. The problem is, it is not givin the right information, actually it doesn't delete the guests from the data base, or so even when a visiter closes the browser it still counts on them.
This is the code:
function online(){ session_start(); include('connect.php'); $guest_timeout= time()- 2 . 40; $member_timeout = time()- 5 . 40; $guest_ip = $_SERVER['REMOTE_ADDR']; $time = time();
if(isset($_SESSION['userName'])){
//if the use is loggedin
$query = mysqli_query($connect, "DELETE FROM active_guests WHERE guest_ip ='".$guest_ip."'");
$query2 = mysqli_query($connect, "INSERT INTO online_users (username, time_visited) VALUES ('".$_SESSION['userName']."', '".$time."' )");
}else{
//guests active
$query3 = mysqli_query($connect, "INSERT INTO active_guests (guest_ip, time_visited) VALUES ('".$guest_ip."', '".$time."')");
}
$query4 = mysqli_query($connect, "DELETE FROM active_guests WHERE time_visited > ".$guest_timeout);
$query5 = mysqli_query($connect, "DELETE FROM online_users WHERE time_visited > ".$member_timeout);
$query6 = mysqli_query($connect, "SELECT guest_ip FROM active_guests");
$online_guests = mysqli_num_rows($query6);
$query7 = mysqli_query($connect, "SELECT username FROM online_users");
$online_users = mysqli_num_rows($query7);
echo "<div class='online'><p>There is currently [" .$online_guests."] site guest(s) and [".$online_users."] online user(s)</p></div> ";
}
?>