Create Hit Counters CGI

Moderator: Lixas

Locked
blue-sky
Posts: 33
Joined: Tue Jun 12, 2007 3:41 pm

Create Hit Counters CGI

Post by blue-sky »

Create Hit Counters CGI

Up until now, every CGI we have used has required the user to hit a 'submit' button on an HTML page, at which point the entire window is replaced by a new page. You could easily write a program using the skills you have already learned to open a count file, add 1, and replace. It would look something like this:

Code: Select all

 #******** BEGIN BODY ******** 
open (GETCOUNT,"<count.log");            #open count log for input 
$counter=<GETCOUNT>;                      #assign contents of file to $counter 
close (GETCOUNT);                              #close access to file 
 
$counter++;                                                 #increase $counter by 1. 
print "$counter hits";                                #print number of hits to users screen 
 
open (PUTCOUNT,">count.log");            #open count log for output 
print PUTCOUNT ($counter);                #replace old counter value with new one 
close PUTCOUNT;                                # close access to file 
 
#******** END BODY ********* 

If we were to call such a program with a SUBMIT button, the current page would dissapear and be replaced by the output of this program. In order to display the hits on our page, we need a way to execute a program when a page loads, and embed the results back in that same page. This method is called a Server Side Include (SSI).

NOTE: Not all web servers support SSI. Some only work if the pagename ends with ".shtml" or ".html-ssi" and some have it completely disabled for security purposes. If you have difficulty with this exercise, check with your system administrator.

Here's how it works:

* Insert the program above into a fresh copy of 'template.txt'. Name the file count.cgi.
* Create a file containing only the starting number of hits. Name this file count.log .
* Open any HTML page, or create one from scratch.
* Insert this line somewhere in the HTML page.
<!--#exec cgi="count.cgi"-->
(If you use a cgi-bin, you should upload the cgi to that, and the command above should read
<!--#exec cgi="/cgi-bin/count.cgi"--> )
* Upload all 3 files to your server.
* Telnet to the perltour folder, and type chmod a+rx count.cgi
* Browse to the html page, and reload it a few times. You should see the number of hits increase.

If nothing shows up, browse to count.cgi to see whether it works, or returns an error. Once you know the cgi works, try renaming the html page with an .shtml extension (for SSI enabled).


anish
Posts: 353
Joined: Fri Apr 27, 2007 12:34 pm
Contact:

Post by anish »

its a cool a cool script i have been using that since many months.
Locked