Search code examples
perlcgihttp-redirect

Perl: CGI redirect from multiple submit buttons


I have a small CGI Script with 2 submit buttons. I want that the current Script redirects the User to another script, depending on which submit button is pressed.

The CGi-Script:

#!/usr/bin/perl -w

# Modules
use strict;
use warnings;
use CGI;

my $q                           = CGI->new();
print $q->header();
print $q->submit(-name=>'button',-value => 'disable');
print $q->submit(-name=>'button',-value => 'enable');

if ($q->param('button') eq "disable"){
         print $q->redirect(-uri=>"http://1.1.1.1./cgi-bin/services/switch_XXX.cgi?disable");
} elsf ($q->param('button') eq "enable"){
        print $q->redirect(-uri=>"http://1.1.1.1./cgi-bin/services/switch_XXX.cgi?enable");
} else {
}

But none of the actions is actually performed. The Error-Log shows the following:

[Tue Mar 06 11:48:44 2018] [error] [client XXXX] Use of uninitialized value in string eq at /var/www/cgi-bin/test.cgi line 23.
[Tue Mar 06 11:48:44 2018] [error] [client XXXX] Use of uninitialized value in string eq at /var/www/cgi-bin/test.cgi line 26.

Could someone of you tell me what causes the error and why the redirect is not working?

Many thanks in advance!


Solution

  • See "Generating a redirection header" in the CGI docs: "If you use redirection like this, you should not print out a header as well."

    The messages you're seeing in the log are referring to the $q->param('button') eq "disable" checks: $q->param('button') is returning undef because the field has not been submitted yet, so you're comparing "disable" to the undefined value. These are warning messages only, that you can avoid by first checking if $q->param('button') has a true value before doing the eq comparison. (Note: In other cases, one might want to use defined to check for undef, because there are some values in Perl that are defined but still false, see Truth and Falsehood - but in this case, both "disable" and "enable" are true values.)

    Also, your submit buttons need to be in a <form>. And note you've got a typo with elsf. This works for me:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use CGI;
    
    my $q = CGI->new();
    if ( $q->param('button') && $q->param('button') eq "disable" ) {
        print $q->redirect(-uri=>"...");
    } elsif ( $q->param('button') && $q->param('button') eq "enable" ) {
        print $q->redirect(-uri=>"...");
    } else {
        print $q->header();
        print $q->start_html;
        print $q->start_form;
        print $q->submit(-name=>'button', -value=>'disable');
        print $q->submit(-name=>'button', -value=>'enable');
        print $q->end_form;
        print $q->end_html;
    }