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

Greetings. I have never really had success with cookies, but am giving it another go. I am able to set a cookie in some cases, yet not set it in another case. Was hoping someone could see what I'm doing wrong, or put in their two bits.

Doesn't work:
if($query{'action'} eq 'Login'){ setCookie(); }else{ head(); #header subroutine fetchCookie(); #displays results ## ... other misc stuff... } sub setCookie { $cookie1 = new CGI::Cookie(-name => 'cookie name', -value => 'value here', -expires => '+3M', -path => '/', ); print "Set-Cookie: $cookie1\n"; print header; print '<meta http-equiv="refresh" content="2">'; }


Works:
setCookie(); if($query{'action'} eq 'Login'){ #setCookie(); }else{ head(); #header subroutine fetchCookie(); #displays results ## ... other misc stuff... } sub setCookie { $cookie1 = new CGI::Cookie(-name => 'cookie name', -value => 'value here', -expires => '+3M', -path => '/', ); print "Set-Cookie: $cookie1\n"; print header; print '<meta http-equiv="refresh" content="2">'; }
I've been at this for hours, and can't seem to find why setting the cookie outside the if statement will work, while having it inside the if statement will not work. I have tried several different ways of doing this, yet nothing. And yes, I have checked to see if $query{'action'} does equal 'Login'. Everything in the if statement works, EXCEPT the setting of the cookie. Any thoughts?

Replies are listed 'Best First'.
Re: Playing with Cookies
by almut (Canon) on Dec 23, 2009 at 00:11 UTC

    If you log the headers of the requests and responses (e.g. with Firefox's "Live HTTP headers" addon), what difference do you see?

    In case nothing else helps ...  the Monks would likely feel more inclined to play with this if you could post a minimal, but complete, self-contained CGI script that allows to reproduce the issue.

Re: Playing with Cookies
by Khen1950fx (Canon) on Dec 23, 2009 at 01:09 UTC
    I came up with this:

    #!/usr/local/bin/perl use strict; use warnings; use CGI qw/:standard/; use CGI::Cookie; my $query = 'action'; if($query eq 'Login'){ (); } else { setCookie(); } sub setCookie { my $cookie1 = new CGI::Cookie(-name => 'cookie', -value => 'here', -expires => '+3m', -path => '/root/Desktop', ); print "\nSet-Cookie: $cookie1\n"; print "Content-Type: text/html\n"; print '<meta http-equiv="refresh" content="2">', "\n\n"; }
    Update: Fixed typo. print \&setCookie; wasn't what I meant. Rather:

    setCookie();

      Do you know what
      print \&setCookie;
      does?
Re: Playing with Cookies
by Anonymous Monk on Dec 23, 2009 at 00:13 UTC
    If you're using CGI to create cookie, print header, use it to set cookie and redirect as well
Re: Playing with Cookies
by Anonymous Monk on Dec 23, 2009 at 23:56 UTC
      Thank you, I was able to use CGI::Session to do what I needed. A lot easier than what I was trying to do with just CGI::Cookies.