Online user counter

By Zen on Jul 15, 2008

See how many ppl are on your site

<?php
// ######################################
//               Toni Zen
//                  (c)
//                2.o.o.8
// ######################################

// Database connection and selection
mysql_connect("localhost", "root", "") or die("Cannot connect");
mysql_select_db("mydatabase") or die("Cannot select database");

// Query for the visitors IP address
$ipQuery = mysql_query("SELECT * FROM user_online WHERE ipaddress = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1");

// Have they visited before?
if(mysql_num_rows($ipQuery) == 1)
{
    // They have visited before
    // Update last active time
    mysql_query("UPDATE user_online SET lastactive = " . time() . " WHERE ipaddress = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1");
}
else
{
    // They have not visited before
    // Insert new row
    mysql_query("INSERT INTO `user_online` VALUES ('" . $_SERVER['REMOTE_ADDR'] . "', " . time() . ")") or die(mysql_error());
}

// Delete any old records (where lastactive < NOW - 5 Mins)
mysql_query("DELETE FROM user_online WHERE lastactive < " . (time() - 300)) or die(mysql_error());

// Query all views
$allViewQuery = mysql_query("SELECT * FROM user_online");

// Get the row count
$onlineCount = mysql_num_rows($allViewQuery);

echo "There is currently " . $onlineCount . " user(s) online";
?>

Comments

Sign in to comment.
Hawkee   -  Jul 15, 2008

You should include the \"create table user_online\" SQL call to make this functional for others to use.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.