Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CGI counter

Status
Not open for further replies.

DEAG

Programmer
Apr 19, 2011
1
0
0
US
Hello everyone,

I'm having trouble getting this script working.

Current issue:
When running the script, I get "You have visited this page 1 time(s)." then when I refresh the page it continue showing "1" instead of incrementing up to "2".

Desired output:
When Launching the script a cookie is created and the counter start at 1. When the page is refreshed or visited again, the number increment up to 2, 3 and so on.

Can someone please help me out with this? Let me know if you need more info...

Here's my script:

#!/usr/bin/perl
print "Content-type: text/html\n\n";
use CGI qw:)standard -debug);
use strict;
use CGI::Carp qw(fatalsToBrowser);
use warnings;

#declare variables
my ($C_visits, $counter, %counter);

#Read the cookie to a variable
%counter = (cookie('$counter'))? cookie('$counter'):'none';

#create cookie
$C_visits = cookie(-name => "MyCookie",
-value => "$counter",
-expires => "+3M");


if (exists $counter{$_}) {
$counter{$_}++;
} else {
$counter{$_} = 1;
}

#send cookie to browser
# print header(-cookie => $counter);

#create Web page
print "<HTML>\n";
print "<HEAD><TITLE>My Counter</TITLE></HEAD>\n";
print "<BODY>\n";
print "<H1 ALIGN=left>Counter<BR></H1><HR>\n";
print "<ALIGN=left>You have visited this page $counter{$_} time\(s\).\n";
print "</BODY></HTML>\n";
 
The cookie needs to be output as part of the header. You currently print out the content type at the start of your script which means that everything after that is part of the html body:

The following will work for you:

Code:
#!/usr/bin/perl -wT

use CGI qw(:standard -debug);
use CGI::Carp qw(fatalsToBrowser);

use strict;
use warnings;

# Read the cookie to a variable
my $counter = cookie('counter') || 0;
$counter++;

# create cookie
my $cookie = cookie(
	-name => "counter",
	-value => $counter,
	-expires => "+3M"
);

# Header with cookie
print header(-cookie => $cookie);

# create Web page
print <<"END_HTML";
<HTML>
<HEAD><TITLE>My Counter</TITLE></HEAD>
<BODY>
<H1 ALIGN=left>Counter<BR></H1><HR>
<ALIGN=left>You have visited this page $counter time(s).
</BODY></HTML>
END_HTML

1;

__END__
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top