Display Current Number Of Online Users Using PHP
Here’s a classic but nonetheless still useful PHP snippet for those of you who’d like to keep tabs on the number of current online users on your website.
This nifty script from PHPSnips checks the number of users within a given specific period of time with the use of a database.
To be able to make it work, set up your database like so:
Now for the code that you’ll need to insert in your functions.php:
<?php session_start(); include"db.php"; # Connect To the database $active_sessions = 0; $minutes = 5; # period considered active if($sid = session_id()) # if there is an active session { # DB connect here $ip = $_SERVER['REMOTE_ADDR']; # Get Users IP address # Delete users from the table if time is greater than $minutes mysql_query("DELETE FROM `active_sessions` WHERE `date` < DATE_SUB(NOW(),INTERVAL $minutes MINUTE)")or die(mysql_error());
# Check to see if the current ip is in the table $sql = mysql_query("SELECT * FROM active_sessions WHERE ip='$ip'"); $row = mysql_fetch_array($sql); # If the ip isn't in the table add it. if(!$row){ mysql_query("INSERT INTO `active_sessions` (`ip`, `session`, `date`) VALUES ('$ip', '$sid', NOW()) ON DUPLICATE KEY UPDATE `date` = NOW()")or die(mysql_error()); } # Get all the session in the table $sessions = mysql_query('SELECT * FROM `active_sessions`')or die(mysql_error()); # Add up all the rows returned $active_sessions = mysql_num_rows($sessions); } # Print the final result echo'<b>Online Now: </b>'.$active_sessions; ?>
Incoming search terms for the article:
- php current time shows users online
- php show number of users online
- php show current users online
- php script to display online users list
- php online users tutorial
- php list show current online users
- current number of online users
- php current online users code
- get current online users list php
- display online users using php