Perl Hit Counter Example

This page provides an example Perl hit counter program. To implement this script program as a server side include it is necessary to place the program in the /cgi-bin directory of the server. This is relative to the location of your root file that begins your webpage.


If you copy this file or edit it using an editor in a Windows operating system and plan to run it on a UNIX or Linux system, make SURE there are no carriage returns embedded in it!!! You will NEED to remove the carriage returns and they WILL be there if you use an editor on a Windows operating system to save your file. If you do not remove all carriage returns, perl may run it correctly from the command line, but it will not run correctly from your webserver. If you have this problem, you will see the contents of your file including comments on your browser when you are testing it.

The Example Code


# This program counts hits, to a web page.
#  It does not count visitors.
# The file name used to count hits is generated using
#  the environment variable DOCUMENT_NAME provided by SSI.
# This feature allows this script to be run from any page,
#  but still keep counts for each page they are run from.
# The name of each file that you are tracking hits on must be different
#   for this to work correctly.
# Of course you'll need a line like:
#   <!--#exec cgi="/cgi-bin/"-->
#  to implement your SSI and your server must support SSI to
#  implement the counter in this manner.
# Set the file name up. 
$HcntFile = "../data/$ENV{'DOCUMENT_NAME'}$ENV{'QUERY_STRING'}hits.dat";
# Open and read the file.  
# $HitCounts is set to 0 if the file doesn't exist. 
open (COUNTHAND, "<$HcntFile");
$HitCounts = <COUNTHAND>;

# Close the file input and open it to truncate output
# Should we worry about locking the file in case another process
#  uses it?  Probably not since if we take that many hits
#  missing a few won't matter and we're too busy to be concerned.
close (COUNTHAND);
open (COUNTHAND, ">$HcntFile");

# Increment $Counter, then write it back out. Put up a message 
# with the new value. Close the file and exit. 
$HitCounts += 1;
print COUNTHAND $HitCounts;
# flock (COUNTHAND, 8);
close (COUNTHAND);
print "Content-type: text/html", "\n\n";        # MIME header.
print "<HTML>", "\n";
print "<HEAD>";
print "<TITLE>General Hit Counter</TITLE>", "\n";
print "</HEAD>", "\n";
print "<BODY>", "\n";
print "<center><H3>Hits on this Page: $HitCounts.</H3></center>\n"; 
print "</BODY>", "\n";
print "</HTML>", "\n";

# End

Implementing in the HTML file

  1. Rename your HTML file so it has a filename with a SHTML extension. The file "myfile.html" would become "myfile.shtml".
  2. Add the following line in your file where you want the output of server side script to be located:

    <!#exec cgi="/cgi-bin/">