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

{ unless (lc($::cgi->https()) eq 'on') { $string = 'https://' . $::cgi->server_name() . $::cgi->url(absolute=>1 +) . '?whocalledme=' . $whocalledme; print $::cgi->redirect($string); exit 0; }
Thats a bit of code I have to ensure the script uses SSL. If that's insecure for some reason please let me know.

Anyway, that bit of code has to go in all my scripts, and so I'd like to put it in a sub() and just call the sub. Problem is i'm using strict (no global variables) and it doesn't seem to work correctly when I pass it the $cgi object.

Is there a trick to passing CGI? is there a better way to do this? Thanks monks.

Replies are listed 'Best First'.
Re: pass cgi object?
by Joost (Canon) on Oct 22, 2004 at 19:56 UTC
    You are not passing a CGI object all. You're counting on the $cgi variable being a package variable in package main. This won't work when someone uses a lexical $cgi variable, or just any other variable name.

    Since you're obviously worrying about security, I wonder if you're using the $:: prefix to circumvent the strict pragma (and if so, why?). Please be careful.

    Also, if I understand the docs correcty, $cgi->https() does not necessarily return 'on' for a https connection but some value that's true.

    Anyway I would probably use a subroutine and pass the object in explicitly, more or less like this:

    my $q = CGI->new; check_https($q); sub check_https { my ($cgi) = @_; unless ($cgi->https) { my $url = $cgi->url(-path_info=>1, -query =>1); s/^http:/https:/ or die "Unsupported URI scheme, or https detecti +on error"; print $cgi->redirect($url); exit; } }
    Ofcourse, this doesn't handle POST requests well.

    edit: fixed typo.

Re: pass cgi object?
by tall_man (Parson) on Oct 22, 2004 at 19:47 UTC
    "use strict" doesn't mean "no global variables", it means "if you use a global it must be qualified with a package name". Since your global is qualified with "$::", which is the same thing as "$main::", you should have no problem with it.

    Maybe we need to see your subroutine code.