image\overbutt.gifCreating a hit counter using Perl

You can create a hit counter using Perl. A hit counter keeps track of the number of HTTP clients that visit your Web site. You can create the file using a text editor. You must save the file as a .cgi file, which is called by an SSI directive. The cgi file created in this example reads and writes to a file called FileCount. The FileCount file stores the number of hits to the Web site. For example, if the FileCount file stores the value 10, and a new hit occurs, the HTTP server calls the counter.cgi file. The counter.cgi file reads the FileCount file, increments the number by one, and stores 11 to the FileCount file. This process is repeated each time an HTTP client accesses or refreshes the Web page.

Before you create the following Perl file, you must create a new file called FileCount. For information on how to create a new file in Corel LINUX, see the Corel LINUX User Guide. Place FileCount in the same directory as the HTML file that has the SSI directive that calls the Perl file. You must change the permission of FileCount and give all users read/write privileges. If you do not change the read/write privileges of FileCount, the HTTP server cannot write to it. For information about changing the permission of a file, see the Corel LINUX User Guide.

To create a hit counter in Perl

1. Click Application Starter, Utilities, Text Editor.

2. Create the Perl file.

You can refer to the following Perl file for a reference.

3. Save the Perl file as counter.cgi

image\nicon.gif Notes

 

#!/usr/bin/perl

print "Content-Type:text/html\n\n";

 

#*** Place the counter file where the HTTP server can locate it!!

$fileCount = "/var/www/fileCount";

 

#*** Call the openFile Function!

&openFile;

 

#*** Create a document buffer

$myDoc = "/";

 

#*** intialize a new variable

$found = 0;

 

for $myLine (@counts) {

chomp ($myLine);

($page, $countIndex) = split(/ /, $myLine);

 

$page=~s/'//g;

 

if ($page eq $myDoc)

{

$countIndex++;

$found = 1;

 

 

$myLine = "'$page' $countIndex";

$found_count = $countIndex;

}

 

#*** Add the the value of $myLine to CountFresh

push (@CountFresh, $myLine);

}

 

if ($found ==1){

$countIndex = $found_count

} else {

$countIndex = 1;

push (@CountFresh, "'$myDoc' 1");

}

 

#*** Sort the contents of CountFresh

@CountFresh = sort(@CountFresh);

 

#*** Update the count file. Call the SaveFile Function

&SaveFile;

 

sub openFile

{

#*** Open the file

open (CFILE, $fileCount);

 

#*** Read from the file

@counts=<CFILE>;

 

#*** Close the file object

close(CFILE);

}

 

#*** Create the save file function!!!

sub SaveFile

{

 

#*** Open the file

open (CFILE, ">$fileCount");

 

for $myLine (@CountFresh)

{

#*** Write to the file!

print CFILE "$myLine\n";

}

 

#*** Close the file

close CFILE;

}

print "$countIndex\n";