A Simple Cookie Example
#!/usr/bin/perl -w
use CGI qw(:standard);
use CGI::Cookie;
use CGI::Carp qw(fatalsToBrowser);
%info = cookie("data");
if (param("Save Form"))
{
$info{'name'} = param('name');
$info{'address'} = param('address');
$info{'email'} = param('email');
$cookie = cookie(-name => "data", -value => \%info, -expires => '+1y');
print header(-cookie => $cookie),
start_html,
p(strong("See you later!")),
end_html;
}
elsif (param("Submit Form"))
{
$cookie = cookie(-name => "data", -value => \%info, -expires => '-1d');
$info{'name'} = $info{'address'} = $info{'email'} = "";
# Cookie cleared, reprint form!
print_form($cookie, \%info);
}
elsif (!param())
{
# See if %info defined because cookie from previous session exists
if (!defined(%info))
{
$info{'name'} = $info{'address'} = $info{'email'} = "";
print_form(undef, \%info);
}
else {print_form($cookie, \%info)}
}
sub print_form
{
my ($cookie, $info) = @_;
print $cookie ? header(-cookie => $cookie): header;
print start_html,
start_form,
p("Name: "),
textfield(-name => 'name', -value => $info->{'name'},
-override => 1),
p("Address: "),
textfield(-name => 'address', -value => $info->{'address'},
-override=>1),
p("Email: "),
textfield(-name => 'email', -value => $info->{'email'},
-override => 1),
submit(-name => "Save Form"),
submit(-name => "Submit Form"),
reset,
end_form,
end_html;
}