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

For an affiliate click tracking program, when someone clicks one of our affiliate links, I want to set a cookie that contains a simple integer affiliate_id. I'm using CGI::Application and this is driving me batty. First I tried this (inside a CGI::Application run-mode):
my $url = $cgi->param('url'); my $cookie = $cgi->cookie( -name => 'affiliate_id', -value => $aid, -path => '/', -domain => $ENV{'HTTP_HOST'}, -secure => 0, -expires => '+3d' ); $self->header_add(-cookie => $cookie); $self->header_add(-redirect => $cgi->redirect($url));
It redirects, but it refuses to set the cookie. I have telnetted in and no cookie header is ever sent.

I also tried this variation:
$self->header_add(-cookie => [$cookie]);
but it made no difference, still refused to set the cookie.

So then, I tried using CGI directly like this:
print $cgi->header( -cookie => $cookie, -redirect => $cgi->redirect($url) );
Same thing happens, no luck with the cookie, although it redirects.

I also tried just setting the cookie and returning nothing from the run mode, and it always prints "1/8" - I have no idea where that is coming from or why it is printing that.

Finally, after running a super search here, I did this:
$self->header_type('redirect'); $self->header_props( -url => $url, -cookie => [$cookie] );
This seems to be working fine, but I am wondering why all this is so flaky - I should be able to use header_add() right? And I should be able to print directly as well, right?

Update:
I'm using mod_perl, CGI.pm version 3.04
CGI::Application Version 3.31
All packaged by debian.

Replies are listed 'Best First'.
Re: CGI::Application, cookies, and redirects
by astroboy (Chaplain) on May 23, 2005 at 22:52 UTC
    From my reading of the doco, this is the way it should work. Have a look at the section "IMPORTANT NOTE REGARDING HTTP HEADERS." In their example, they set the type and props, just as you have in your example that works
Re: CGI::Application, cookies, and redirects
by johnnywang (Priest) on May 24, 2005 at 04:32 UTC
    From the code, headers will only be sent if header_type is not "none", and when you call header_add(), you have to first make sure the header type is not "none" (i.e., "header" or "redirect"), which probably explains why the last of your code works becuase you set the header_type first. What bothers me a little bit is that CGI::Application::new() sets the header to "header" by default, are you doing something else that might change it to "none"?
      I don't think so. I'm going to explicitly set it to "header" tomorrow when I have the code open again and see if that works. Thanks a lot for your help.