#!/usr/bin/perl -T ## # Supposed to be simple cgi example # with sessions and templates. ## use strict; use warnings; use diagnostics; use CGI qw/:standard/; use CGI::Carp qw/fatalsToBrowser/; use HTML::Template; use CGI::Session; use DBI; use Data::Dumper; my $DEBUG = 1; my $TMPL_ROOT = '/htdocs/tmpl'; my $cgi = CGI->new(); my $dbh = DBI->connect( 'dbi:mysql:sessions', 'dbuser', 'dbpass', { 'RaiseError' => '1', 'PrintError' => '1', 'AutoCommit' => '1' }) or die $DBI::errstr; my $sess = CGI::Session->new("driver:mysql;serializer:storable", $cgi, {'Handle'=> $dbh }) or die( CGI::Session->errstr ); print $sess->header, $cgi->start_html(-title=>"$0"); if ($cgi->param('.reset')) { $sess->clear(); print $cgi->h3('A session has been cleared'); } if ($sess->param()) { print $cgi->h3('A session has been loaded'); } else { print $cgi->h3('This is a new empty session'); } # checkbox group if (my @checks = $cgi->param('words')) { my $cxhist = ( $sess->param("words.cxhist") or {} ); my %cx = map { $_ => 1 } @checks; foreach (keys %cx) { # maintain a list of boxes I check $cxhist->{"$_"}++; # store a bool for html template $sess->param(-name=>"words.$_", -value=>1); } foreach (keys %{$cxhist} ) { # look for unchecked boxes to clear if (! $cx{$_}) { $sess->param(-name=>"words.$_", -value=>0); } } # maintain history of checkboxes $sess->param(-name=>"words.cxhist", -value=>$cxhist ); } # select if (my $selected = $cgi->param('color')) { # save selected color in the session my $selhist = ( $sess->param("color.selhist") or {} ); $selhist->{$selected}++; $sess->param(-name=>"color.$selected", -value=>1); # clear old unselected colors out of the session foreach (keys %{$selhist}) { if ( $_ ne $selected ) { $sess->param(-name=>"color.$_", -value=>0); } } # maintain history of selections $sess->param(-name=>"color.selhist", -value=>$selhist ); } # Save everything for next request $sess->save_param(); # print out page loading stuff from session or cgi my $tmpl = HTML::Template->new(filename=>"$TMPL_ROOT/test.tmpl", associate=>$sess); # debug option to show session $DEBUG && $tmpl->param('session.dump', Dumper($sess)); print $tmpl->output(); print $cgi->end_html;