Main Menu
Contact Bill FAQ
Linked In
Hire Bill
Bill’s Music
BW Whois
Boulder Pledge
CGI Scripts
CMS Project
Music DB
Creative HTML
The CGI Book
Perl Book
The End
· Sponsors · video tutorials
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/" -->

The result should look something like this:


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 Copy/paste this code into your text editor, and make sure that the line

is the first line in the file.

# by Bill Weinman <>
# 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";

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

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


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

# 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> );
    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 );
    flock( $f, LOCK_UN );

Of all the things I've lost, I miss my mind the most.
At BHG Worldwide Headquarters it is now thirteen till eleven, on Wednesday, 24 July 2024.