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

Hi, I've set up a script to send a cookie using CGI.pm. It also proceeds to send an HTML page afterwards. The problem is the browser (mozilla 1.3) only displays the following:

<html><body></body></html>

Is this a problem with sending multiple headers? If so how do I get around it. Thanks for your time.

Replies are listed 'Best First'.
Re: Sending a cookie header and HTML output
by zby (Vicar) on Jun 24, 2003 at 10:29 UTC
    You should send just one header section. Like this:
    use CGI; . . . print header(-type=>'text/html', -cookie=>$your_cookie ...)
    So once more - just one header section but with multiple information inside it.

    Update: added the word 'section' to be more prcecise - inspired by tfc22.

      Just to clarify:

      print header(-cookie => $cookie); ... print header(-type => 'text/html');

      Then printing the HTML won't work?

        It won't. To see why just capture the output of executing the program to a file. The header according to HTTP specification is only the text untill the first blank line (or every character until two consecutive new lines). You'll see that this program would output a blank line between parts of what should be the header.
Re: Sending a cookie header and HTML output
by tcf22 (Priest) on Jun 24, 2003 at 13:49 UTC
    You can send multiple headers. A call to header() with multiple parameters prints multiple headers to the browser. Calling
    print header(-type=>'text/html', -cookie=>$your_cookie ...)
    would actually print out
    Content-type: text/html\n Cookie: $your_cookie\n\n
    To give you a better answer than you can print out more than one header, I need to see some sample code.

      Just thought of another problem: say I'm authenticating a user, I check for a cookie containing a session ID, if the cookie doesn't exist I check for login parameters from a form. If the login is valid, I want to set a cookie containing a session ID. I have all the preceeding in a subroutine which I call, then later I will print out an HTML document (say: a welcome message) - which is the best way to handle this? Should I send the cookie & header, let the script finish running then send the HTML (the actual data, not the header), or should I return the cookie to the calling code and send it only right before the HTML? Thanks.

        I prefer to send all of my output(including the headers) at the end of the script, after all of the processing has been done. The reason I do it that was is because if an error occurs during processing, you don't have an half loaded page, then an error. I can just scrap all of the legitiment output and display the error message.