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

I can hear the screams now. Yes, another cookie question. Before posting I did read a previous node which came close, but I'm still not getting it. So, before I go back to the dreaded javascript....

Here I check to see if the user has logged in. If they haven't, or it's been > 15 min, they are sent to the login script. Otherwise, a new "session" is started. I'm able to set the cookie, but I'm not able to read it. In the aforementioned node, is chromatic saying that I can't try to read a cookie and then set one at the same time? If so, how am I to get around it? Thanks in advance.
#!/usr/bin/perl print "Content-type: text/html\n\n"; use strict; use CGI; my $query = new CGI; my $username = int(rand 1000000); my $cookie = $query->cookie('xmsessionID'); #check for cookie if (!$cookie) { print "No cookie<br>"; #for testing purposes goto &login } else { print "Cookie found: $cookie<br>"; #for testing purposes } #-------- write new cookie ----------- my $newcookie = $query->cookie(-name=>'xmsessionID', -value=> $username, -expires=>'+15m'); print $query->header(-cookie=>$newcookie);

—Brad
"A little yeast leavens the whole dough."

Replies are listed 'Best First'.
Re: Not able to set and retrieve cookie
by b10m (Vicar) on Apr 28, 2004 at 20:10 UTC

    Cookies are part of the headers, so you can't first send Content-type: text/html\n\n, then some text and then the cookie header. Nope, you need to send it before any output.

    --
    b10m

    All code is usually tested, but rarely trusted.
      b10m, thanks. That was it. Basically my cookie code was fine, it was just using the print statements for testing that was throwing me off. As soon as I moved the print "Content-type..."; below the cookie handling, everything was fine.
      #!/usr/bin/perl use strict; use CGI; my $query = new CGI; my $username = int(rand 1000000); my $result; my $cookie = $query->cookie('xmsessionID'); #check for cookie if (!$cookie) { $result = "No cookie<br>"; #goto &login; } else { $result = "Cookie found: $cookie<br>"; } #-------- write new cookie ----------- my $newcookie = $query->cookie(-name=>'xmsessionID', -value=> $username, -expires=>'+1m'); print $query->header(-cookie=>$newcookie); print "Content-type: text/html\n\n"; print $result,"<br>";

      —Brad
      "A little yeast leavens the whole dough."

        If you are using CGI (which you rightly should be as you are), you shouldn't manually output your headers. Calling $query->header(); will do it for you, and $query->header( -cookie => $newcookie ); will print out the Set-cookie header, as well as the Content-type header.