in reply to Not able to set and retrieve cookie

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.
  • Comment on Re: Not able to set and retrieve cookie

Replies are listed 'Best First'.
Re: Re: Not able to set and retrieve cookie
by bradcathey (Prior) on Apr 28, 2004 at 21:09 UTC
    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.

        Sorry, I didn't quite follow you, but I wish I did. If you, whoever you are, get a chance, can you expound a bit? I can't tell if I was doing it right or if you were suggesting another way. Thanks.

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