The basic purpose of a Web site counter is to record the number of people who have visited a particular page.
There are four simple steps involved in building a counter:
Step One: Create a text file on the server called counter.dat with a single number in it.
This file will store the number of visitors.
Change its permissions to 666 to make it read and writeable.
Step Two: When someone visits the site, this file is accessed, the number stored within it is obtained and incremented by one, and then displayed to the visitor.
Step Three: The new number is written back to the file.
Step Four: Go back to Step Two.
Here's the code:
#!/usr/bin/perl
# counter.cgi - count visitors to page
# open a file handle to read the contents of the file "counter.dat"
# this file contains the number of visitors before the
# current user.
open (COUNT, "<counter.dat");
# assign the value that is stored in the file handle in a temporary variable
$counter = <COUNT>;
close (COUNT);
# open the file handle to write the new number back to the file
open (COUNT, "> counter.dat");
# increment the counter variable by one
$counter += 1;
# write the new number
print COUNT "$counter";
close (COUNT);
# now display the HTML code
print "Content-type: text/html\n\n";
# print the new counter value
print "<html>\n";
print "<body>\n";
print "<h1>Your are visitor number";
print "$counter </h1>\n";
print "</body>\n";
print "</html>";
Exercise
1. Create the counter.dat file in the cgi-bin directory.
2. Using the code above create a file called counter.pl in the cgi-bin directory.
3. From the command line execute the perl script.
4. Build a web page with a link to the perl script and test your counter with a web browser.
You can easily extend the functionality of this counter to store the IP address, the browser type, the referrer URL and other visitor statistics by making use of the Environment variables, but I'm going to leave that as an exercise for you.