Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Simple Hit Counter

by Anonymous Monk
on May 29, 2006 at 01:59 UTC ( #552233=sourcecode: print w/replies, xml ) Need Help??
Category: Web Stuff
Author/Contact Info GreyFox greyfox@30gigs.com greyfox@hacktek.net
Description: This is a simple hit counter I threw together for my website. Nothing fancy, it just
#!/usr/bin/perl -w
#Simple hit counter

#To include in a webpage (HTML), put <!--#exec cmd="PATHTOCGISCRIPT.cg
+i"--> in the document
#Replacing PATHTOCGISCRIPT with the url to the CGI script (this script
+).
#For PHP, within the <?php and ?> tags, include "virtual("PATHTOCGISCR
+IPT.cgi");"
#without the quotes.  Also, you need to create
#a file named hits.txt for the script to access.  It can
#be blank

#Script copyright 2006 GreyFox of hacktek.net 


#VARIABLES

$file = "hits.txt";

#READING

open (COUNT,"<$file") or die "Counter error 1";
$hits = <COUNT>;
close COUNT;

#INCREMENTING

$hits++;

#CONTENT

print "Hits: $hits";

#SAVING

open (COUNT,">$file") or die "Counter error 2";
print COUNT $hits;
close COUNT;


Replies are listed 'Best First'.
Re: Simple Hit Counter
by gloryhack (Deacon) on May 29, 2006 at 20:55 UTC
    See perlopentut for a correct though still largely useless way to do this. The bit you want is in the "File Locking" section.
Re: Simple Hit Counter
by CountZero (Bishop) on May 29, 2006 at 19:37 UTC
    And of course the value of the counter is meaningless. The only thing it counts (if at all -- see the race condition/locking issue) is how many times the script ran and who would be interested in that?

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Simple Hit Counter
by GreyFox (Initiate) on May 29, 2006 at 02:00 UTC
    Ok. I was logged in when I clicked on the link to post this. Oh well. I did make this.
      It's nice and simple, indeed. But (sorry ;) you will run into problems with it. As soon as two people access the counter at the same time, funny things will happen to your counter, because you don't use file locking.

      Have a look at perlfaq5 - web hit counter, or better yet, File::CounterFile.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://552233]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2019-12-07 09:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (160 votes). Check out past polls.

    Notices?