Users Online
By: Daniel

Keeping track of how many users have been on your website is very easy. This can be done with some basic MySQL code and the date() function. All you have to do is keep track of the users IP address and time they were last on the page. Lets get to some code:

<?
$server = 'localhost';
$user = 'root';
$pass = '';
$db2 = 'online';

$db = mysql_connect($server, $user, $pass) or die("Could not connect.");
if(!$db) 
	die("no db");
if(!mysql_select_db("$db2",$db))
 	die("No database selected.");
$server_time=date("U");
$client_ip=$_SERVER['REMOTE_ADDR'];

$query = mysql_query("SELECT * FROM current_users WHERE ip='$client_ip'");
$check = mysql_fetch_array($query);
if($check) {
	$update="UPDATE current_users set time='$server_time' where ip='$check[ip]'";
	mysql_query($update) or die("Unable to process update: " . mysql_error());
} else {
  $sql = "INSERT INTO `current_users` (`ip`, `time`) VALUES ('$client_ip', '$server_time')";
  $result = mysql_query($sql) or die("Unable to process insert: " . mysql_error());
}
$time=$server_time-1800;
$remove = "DELETE from current_users WHERE time<'$time'"; // Remove users outside time limit
mysql_query($remove) or die("Unable to delete: " . mysql_error());

// Show the count
$sql2 = mysql_query("SELECT ip FROM current_users" );
$currentVisitors = mysql_num_rows($sql2);
echo 'There have been '.$currentVisitors.' users online in the last 30 minuets.';
?>

The first query checks to see if your IP address is in the database. If your IP address is in the database it updates the time. If your IP address is not in the database, we then insert the time and your IP address.

To eliminate old users we automatically remove users who have been online after 30 minutes(1800 Seconds). If you want to change the time delay just multiply 60 times the number of minutes.
10 Minutes = 600
15 Minutes = 900
20 Minutes = 1200
30 Minutes = 1800
1 Hour = 3600

Make sure you create a database and apply your settings to the variables at the top.
Insert the following SQL query into your database:

CREATE TABLE `current_users` (
`ip` varchar(30) NOT NULL default ”,
`time` varchar(30) NOT NULL default ”
) TYPE=MyISAM;

Just save this as online.php and include this in your page.

1 Star2 Stars3 Stars4 Stars5 Stars (15 votes, average: 3.80 out of 5)
Loading ... Loading ...

3 Responses to “Users Online”

  1. Billy Says:

    thanks a lot. Just what I was working for and easy to mod. I had trouble using the create table code above, so I had to create the table manually.

  2. Sam Says:

    CREATE TABLE `current_users` (
    `ip` VARCHAR( 30 ) NOT NULL ,
    `time` VARCHAR( 30 ) NOT NULL
    ) TYPE = MYISAM ;

    this table code worked for me.

  3. Tito Says:

    ` you replace with “

Leave a Reply

geovisitors