I wrote a small perl cgi code to test set/read/delete cookie as follows.
After submit, at the first time, the 'if' block in red does not get executed. Instead, I still get the form but with the html header (Content-Type: text/html printed out on my browser. At this point, if I hit 'F5' key to reload, then the 'if' block in red get executed. And what I see on my browser is like this:
And worse, the cookie never got deleted! I keep getting the same information shown above after repeating pressing F5 key.
What I expect is that after clicking 'Submit' button, I should see “Cookie is found!!” ONLY. Next, if I press F5 key, I'll get the form again, 'cuase the cookie should be deleted.
Could someone tell me what I did wrong in my code? Thanks.
Code:
use strict;
use CGI::Pretty qw( :html3 );
use CGI::Cookie;
local $| = 1;
my $cookieName = 'ckname';
my $userInput = 'input';
my $q = new CGI::Pretty;
if($q->param('ok') == 1) {
my $val = $q->param($userInput);
my $ck = new CGI::Cookie(-name=>$cookieName,-value=>$val);
print $q->header(-cookie=>$ck);
}
my %cookies = fetch CGI::Cookie;
[COLOR=red]
if(defined($cookies{$cookieName})) {
my $ck = new CGI::Cookie(-name=>$cookieName,-value=>'');
print $q->header(-cookie=>$ck);
print "Cookie is found!!";
exit;
}
[/color]
my $html = $q->start_html();
$html .= $q->start_multipart_form(-name=>'theForm');
$html .= $q->hidden(-name=>'ok',-value=>'1');
$html .= $q->div($q->label('Type something: '), $q->input({-name=>$userInput,-type=>'text'}));
$html .= $q->div($q->submit());
$html .= $q->end_form();
$html .= $q->end_html();
print $q->header;
print $html;
After submit, at the first time, the 'if' block in red does not get executed. Instead, I still get the form but with the html header (Content-Type: text/html printed out on my browser. At this point, if I hit 'F5' key to reload, then the 'if' block in red get executed. And what I see on my browser is like this:
Code:
Set-Cookie: ckname=; path=/ Date: Fri, 05 Oct 2007 20:29:45 GMT Content-Type: text/html; charset=ISO-8859-1 Cookie is found!!
And worse, the cookie never got deleted! I keep getting the same information shown above after repeating pressing F5 key.
What I expect is that after clicking 'Submit' button, I should see “Cookie is found!!” ONLY. Next, if I press F5 key, I'll get the form again, 'cuase the cookie should be deleted.
Could someone tell me what I did wrong in my code? Thanks.