BW
Main Menu
Home
Contact Bill
lynda.com FAQ
Facebook
Linked In
Twitter
AMTP
Bio
Hire Bill
Bill’s Music
BW Whois
Boulder Pledge
UBE-Related
Blog
CGI Scripts
CMS Project
Music DB
Creative HTML
The CGI Book
Perl Book
BillyDos
Privacy
The End
· Sponsors ·
lynda.com video tutorials
amazon.com
Rheumatoid Arthritis
Site Design: Bill Weinman

CGI Scripts by Bill Weinman

bw-counter [perl] [python]

This is a simple hit counter for your web page. It is run from a server-side include (SSI). This version is written in Perl. There is also a Python version.

On an Apache server you put something like this in your page:

  <!--#include virtual="/bw-counter/bw-counter.pl" -->

The result should look something like this:

2,196

You will need to create a file for the count, and make sure the web server has read and write permission for that file (i.e., chmod 666 filename on a Unix system). The full path to that file should go in the $count_file variable near the top of the script.

Here is the source code for bw-counter.pl. Copy/paste this code into your text editor, and make sure that the line

#!/usr/bin/perl
is the first line in the file.

#!/usr/bin/perl
# bw-counter.pl by Bill Weinman <http://bw.org/>
# Copyright (c) 1995-2010 The BearHeart Group, LLC
# updated 2010-02-02
#
# A simple incremental counter for a web page. (perl version)
#
# The author grants permission to use and modify this program as you like.
# All other rights and ownership are reserved by the author.
#

use strict;
use warnings;
use IO::File;
use Fcntl ':flock';

my $count_file = "/full/path/to/count";
main();

sub main
{
    print "Content-type: text/html\n\n";

    my $count = readfile($count_file);
    chomp $count;
    $count++;
    print comma($count);
    writefile( $count_file, "$count\n" );

    exit;
}

sub error
{
    my $e = shift;
    print "$e\n";
    exit;
}

# commas for thousands separators
sub comma
{
    my $number = shift;
    $number += 0;    # make sure it's a number;

    while ( $number =~ s/ ( .*\d ) ( \d \d \d ) /$1,$2/xg ) { }
    return $number;
}

sub readfile
{
    my $filename = shift or return;
    my $f = new IO::File("<$filename");
    error("cannot open $filename ($!)") unless $f;
    my $string = join( '', <$f> );
    $f->close;
    return $string;
}

sub writefile
{
    my $filename = shift or return;
    my $data = shift || '';
    my $f = new IO::File(">$filename");
    error("cannot write $filename ($!)") unless $f;
    flock( $f, LOCK_EX );
    $f->print($data);
    flock( $f, LOCK_UN );
    $f->close;
}


Go ahead, we're cleared for weird!
At BHG Worldwide Headquarters it is now three o'clock, on Friday, 19 April 2024.
·/.