Posted: Sun Jun 26, 2005 6:33 pm Post subject: CGI Simple Online Activity Logger
This is a simple script I wrote for logging how many guests are visiting your website. I made this mostly for my webcam page, so I can see how many people are watching me (just fun stuff to know), but also made it more dynamic for uses on other things.
Features
- Customizable: you can change the message printed, etc.
- Functions as a JavaScript and can be embedded anywhere.
- Can keep track of multiple purposes.
- Small file size.
- Simple.
Multiple-purpose Usage
To use this file to keep track of multiple different user counts, in the configuration (see below) change $many to 1, and on its use put in the query string the unique ID for that tracker (i.e. "online.cgi?homepage").
Anyway, here's the code, most of the configuration you'll need is at the top. The code is really simple so if you want to customize it even more, go right ahead.
Code:
#!/usr/bin/perl -w
use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
# Directory for keeping data.
my $dir = './online';
# String to be written. Can use special variables:
# @count@ = number of users online
# @id@ = the data tag, for multiple data, defaults to "default"
# <this/that> = if ONE, "this" is used; other, "that" is used.
my $string = '@count@ <person/people> <is/are> watching my cam.';
# Multiple data keeping? (specify ID's as the query string, i.e. "online.cgi?mainsite"
my $many = 0;
# Timeout (in seconds).
my $expire = 60;
#####################
# End Configuration #
#####################
mkdir ($dir) unless -d $dir;
# Initialize variables.
my $id = $ENV{REMOTE_ADDR};
my $tag = $ENV{QUERY_STRING} || 'default';
my $file = $id;
my $count = 0;
# Mark THIS user as online.
if ($many) {
$file = join ('_', $tag, $id);
}
open (WRITE, ">$dir/$file\.txt");
print WRITE time();
close (WRITE);
# Get all online users.
opendir (DIR, $dir);
foreach my $user (sort(grep(!/^\./, readdir(DIR)))) {
open (FILE, "$dir/$user");
my $active = <FILE>;
close (FILE);
# If this user is inactive, unlink the file.
if (time() - $active >= $expire) {
unlink ("$dir/$user");
next;
}
# Only take this file seriously if it needs to be.
if ($many) {
next unless $user =~ /^$tag\_/i;
}
$count++;
}
closedir (DIR);
# Process the string.
$string =~ s~\@count\@~$count~ig;
$string =~ s~\@id\@~$tag~ig;
$string =~ s~\'~\\'~ig;
while ($string =~ /(<(.*?)\/(.*?)>)/i) {
my $code = $1;
my $one = $2;
my $two = $3;
my $new = undef;