Amal Antony
Amal Antony

Reputation: 6807

Perl CGI page visit counter does not increment

I was trying out an elementary Perl/CGI script to keep track of visitors coming to a web page. The Perl code looks like this:

#!/usr/bin/perl
#KEEPING COUNT OF VISITORS IN A FILE
use CGI':standard';
print "content-type:text/html\n\n";
#opening file in read mode
open (FILE,"<count.dat");
$cnt= <FILE>;
close(FILE);
$cnt=$cnt+1;
#opening file to write
open(FILE,">count.dat");
print FILE $cnt;
close(FILE);
print "Visitor count: $cnt";

The problem is that the web page does not increment the count of visitors on each refresh. The count remains at the initital value of $cnt , ie `1``. Any ideas where the problem lies?

Upvotes: 1

Views: 1437

Answers (5)

sameera sy
sameera sy

Reputation: 1718

The most obvious thing that you would have forgotten is to change permissions of the file count.dat Do this :

sudo chmod 777 count.dat

That should do the trick

Upvotes: 0

jacasa
jacasa

Reputation: 9

You will need to close the webpage and reopen it again. Just refreshing the page won't increment the count.

Upvotes: -2

JRFerguson
JRFerguson

Reputation: 7516

Here's an alternate solution that uses only one open() and creates the file if it doesn't already exist. Locking eliminates a potential race condition among multiple up-daters.

#!/usr/bin/env perl
use strict;
use warnings;
use Fcntl qw(:DEFAULT :flock);
my $file = 'mycount';
sysopen(my $fh, $file, O_RDWR|O_CREAT) or die "Can't open '$file' $!\n";
flock($fh, LOCK_EX) or die "Can't lock $file: $!\n";
my $cnt = <$fh>;
$cnt=0 unless $cnt;
$cnt++;
seek $fh, 0, 0;
print ${fh} $cnt;
close $fh or die "Can't close $file: $\n";
print "Visitor count: $cnt\n";

Upvotes: 3

Zaid
Zaid

Reputation: 37146

A few potential reasons:

  • 'count.dat' is not being opened for reading. Always test with or die $!; at minimum to check if the file opened or not

  • The code is not being executed and you think it is

Upvotes: 1

Quentin
Quentin

Reputation: 943556

You never test if the attempt to open the file handle works. Given a file which I had permission to read from and write to that contained a single number and nothing else, the code behaved as intended. If the file did not exist then the count would always be 1, if it was read-only then it would remain at whatever the file started at.

More general advice:

  • use strict; and use warnings; (and correct code based on their complaints)
  • Use the three argument call to open as per the first example in the documentation
  • When you open a file always || handle_the_error_in($!);
  • Don't use a file to store data like this, you have potential race conditions.
  • Get the name of the language correct

Upvotes: 7

Related Questions