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

i have had problems printing the header() too deep within the program. Is their some point at which the header() must be printed or is iit that the scripts i was creating were more likely flawed in some other way
  • Comment on location of header thats setting a cookie

Replies are listed 'Best First'.
Re: location of header thats setting a cookie
by synapse0 (Pilgrim) on Jul 20, 2001 at 08:20 UTC
    The header, in order to work properly needs to be the first thing printed, any whitespace or anything else printed before the header will not allow the header information to accepted as header information by the server.
    -Syn0
      what i am trying to do is create a login that sets a cookie but the way i have it now it created the cookie even if the password it wrong. do you think the sloution of having it print another cgi script that would create the same cookie with the expiration date in the past in the case of an incorect password? or i could put the header() in two if statmets and just be careful not to print before the header()

        Hi, it sounds like a bit of logic failure to me. This is the skeleton of what you want. You certainly don't need two scripts.

        #!/usr/bin/perl -wT use strict; use CGI; my $q = new CGI; my $user_pwd = $q->param('password'); unless (check_password($user_pwd)) { print $q->header("text/html"), $q->start_html("Error"), $q->h1("Wrong Password!"), $q->p("Use back button and try again"), $q->end_html; exit; } # do password OK stuff like set cookie my $cookie = $q->cookie( -name => "id", -value => "foo", -expires=> "+1y" ); print $q->header(-type => "text/html", -cookie => $cookie); # more code here exit; sub check_password { my $pwd = shift; # check pwd here # return true if OK, false if not }

        cheers

        tachyon

        s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

        it's really hard to say w/out seeing the script.. The most I can say is to play with it for a bit to see what is going on. The easiest way to do this (particularily if the server is a unix type machine (i've not tested such a thing on a windows platform) ) is to run the cgi from the cmd line. CGI.pm will allow you to run it, will ask for parameters before running the script, type ctrl-D to end the parameter section and the script will run. From here, you can see if anything is printing before the header section. If it is, you can try and hunt down what exactly is printing.
        -Syn0
Re: location of header thats setting a cookie
by HyperZonk (Friar) on Jul 20, 2001 at 08:22 UTC
    It's difficult to say what your problem is without a code sample; it sounds to big to post, here, though. However, I can say that header must be printed before any other output from the program. If you are printing something else to STDOUT first, header won't do its job.

    Update: Shucks, syn beat me to the punch! :)