Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

CGI::Session Simple Example

by mull (Monk)
on Mar 14, 2006 at 14:55 UTC ( [id://536588]=perlquestion: print w/replies, xml ) Need Help??

mull has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to learn CGI::Session for another project, so I re-wrote the "simple example" script from the CGI.pm documentation to use sessions and HTML::Template.

Working on the "simple example" has me wondering if this is not so simple? It gets a little confusing working with the CGI object, the Session object, and the Templates, and then trying to keep straight in your head how the client is going to interact with the script.

One suprise was that I had to write what seemed to be a lot of extra code just to unset values in the session when they were no longer needed.

Another is that my session doesn't exactly seem to clear correctly.

There is an html template that goes along with this where I just have a bunch of <TMPL_IF> statements looking for which checkbox to select, etc.

I am hoping someone with more experience can point me in the right direction here? I'm not sure if I'm going about this the right way- and I need the concepts clear in my head before I go on to the actual work.

#!/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;

Replies are listed 'Best First'.
Re: CGI::Session Simple Example
by saberworks (Curate) on Mar 14, 2006 at 20:32 UTC
    I recently got bogged down with using HTML::Template and persisting form fields when an error occurred in form processing. What I ended up doing was just using CGI.pm for creating the form fields. Each field can be set a default value by using the -default named parameter. So in this case, I just set the -default to $sess->{'whatever'}, and of course, if key 'whatever' doesn't exist, it just gets undef, no harm, no foul.

    There are other options for prefilling your forms as well. Check out HTML::FillInForm.

    The other thing you can do to simplify your scripts is use something like CGI::Application to organize your data. You can use the prerun/postrun hooks to create and persist your sessions automatically, so when you get down to actually programming logic, you don't have to think about those housekeeping things anymore.

      CGI::Application moves you more from managing individual scripts to a MVC framework. I would suggest that you head this way also.

      CGI::Application also has numerous plugins. There is only for CGI::Session which is alot easier to work with than CGI::Session directly, and there is another plugin for HTML::FillInForm as well.

Re: CGI::Session Simple Example
by DaWolf (Curate) on Mar 15, 2006 at 00:09 UTC
    It gets a little confusing working with the CGI object, the Session object, and the Templates, ...
    Try getting templates out of the equation. Once you get CGI and sessions right it will be easy to re-implement the template back in.

    Just my two cents.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://536588]
Approved by planetscape
Front-paged by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-26 06:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found