Adding an Access Counter
A text access counter
The Increment subroutine
The complete text access counter script
Seeding the Counter
Adding the Counter to Your HTML Page
With Server Side Includes
Without Server Side Includes
Creating the Template File
Modifying the access.pl Script
A graphical access counter
Incrementing the Counter
Creating the GIF Image
Returning the Graphical Counter Image
The Graphical Counter Script
Calling the Counter with the <IMG> Tag

[Previous] [Next]


The complete text access counter script


Now that it can increment the counter, your script just needs to return the value of the counter for display in the Web page. You can do this by using the following three lines of Perl:
 $access_number = &Increment;
 print "Content-type: text/html\n\n";
 print $access_number;


The first line calls the Increment subroutine and assigns the return value to the variable $access_number. The next line prints the required parsed header. The last line prints the value of the access counter.

You can place the preceding lines of Perl code, along with the code for the Increment subroutine, in a file called access.pl. Listing 2 shows the complete access.pl file. Notice that the global variable $file is set at the beginning of the file and is used within the Increment subroutine. Also, if you use this counter on a machine running a version of Windows, remove the first line and change the path for the count.dat file.

Listing 2: The access.pl file
#!/usr/local/bin/perl

 # All users need to change the value of this
 # variable to the path for their machine. Windows
 # users need to use a format similar to
 # "c:\\robertm\\count.dat"
 $file = "/users/robertm/count.dat";

 $access_number = &Increment;
 print "Content-type: text/html\n\n";
 print $access_number;

 sub Increment {
   local ($count);

   # Get the current value of the access counter.
   open(COUNT, "$file") || die "Content-type: text/html\n\nCannot open
   counter file!";
   $count = <COUNT>;
   close(COUNT);

   # Increment the access counter
 ;
   $count++;

   # Store the value of the counter in the counter file.
   open(COUNT, ">$file") || die "Content-type: text/html\n\nCannot open
   counter file!";
   print COUNT $count;
   close(COUNT);

   return $count;
 }






[Previous] [Next]