Hi guys,

If you want a simple “Who is Online” for your website, just read the post. It’s really quite simple.

Please note, I’ve used a PHP/MySQL wrapper for handling my connections to the database. (http://www.ricocheting.com/code/php/mysql-database-class-wrapper-v3)

I created a class to handle the database-specific code:

<?php

class People {

	function exists($ip) {
		$db = Database::obtain();

		$sql = "SELECT 1 FROM " . tbl_people . " WHERE ip = " . ip2long($ip);
		$row = $db->query_first($sql);

		if (!empty($row)) {
			return true;
		}
		else {
			return false;
		}
	}

	function online() {
		$db = Database::obtain();

		$sql = "SELECT COUNT(*) as counted FROM " . tbl_people;
		$row = $db->query_first($sql);

		return $row['counted'];
	}

	function insert($ip) {
		$db = Database::obtain();

		$data['ip'] = ip2long($ip);
		$data['time'] = "NOW()";

		$pid = $db->insert(tbl_people, $data);

		return $pid;
	}

	function update($ip) {
		$db = Database::obtain();

		$data['time'] = "NOW()";
		$db->update(tbl_people, $data, "ip=" . ip2long($ip));
	}

	function truncate() {
		$db = Database::obtain();

		$sql = "DELETE FROM " . tbl_people . " WHERE time < SUBTIME(NOW(),'0 0:10:0')";
		$db->query($sql);
	}

}

?>

The flow goes like this:

  1. Someone visits your website, so we check to see if their IP address already exists in the database
  2. If it doesn’t we add their IP address
  3. If it does, we update the timestamp associated with that IP address
  4. Then we run truncate the table of old timestamps. (10minutes)
  5. Finally, we count how many rows are in the table, and output that as the amount of people on the website.

Put that all together:

<?php
require_once('class_people.php');
$people = new People;

$ip = $_SERVER['REMOTE_ADDR'];
if (!$people->exists($ip)) {
	$people->insert($ip);
}
else {
	$people->update($ip);
}

$people->truncate();

echo $people->online();
?>

I hope that covers it! :-) The tutorial should be simple enough for you to use basic PHP mysql connection code, PDO etc. If you have a problem, don’t hesitate to ask.

Tags: ,

· · · ◊ ◊ ◊ · · ·