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

Hello,
All powerful monks I seek some wisdom, I started to built a apache module to check if a cookie exist, if not it would check authentication against a custom database. if granted I would like to set/drop a encrypted cookie on the client. Then as the client moves through out the site I can check for the cookie and to make sure its valid.
So I'm at the point where I create a cookie and I have checked it and it is created, it seems I can never get it to drop on the clients browser. I have tried a number of ways but none work.
Here is some code
sub new_cookie {
my($product, $plaintext,$cipher) = @_;
my $ciphertext = $cipher->encrypt_hex($plaintext);
return new CGI::Cookie(
-name=>$product,
-value=>$ciphertext,
-path=>'/',
-expires=>''
);
}

$new_cookie_product = new_cookie($product,$plaintext,$cipher);
I have tried a number of things to drop the cookie on the client, but none of the examples I have worked.

Replies are listed 'Best First'.
Re: CGI:Cookie, Apache2, Mod_perl2
by lihao (Monk) on Jun 13, 2008 at 18:33 UTC

    Add the following line to send out the cookie:

    $r->err_headers_out->set('Set-Cookie', $new_cookie_product);

    lihao

Re: CGI:Cookie, Apache2, Mod_perl2
by almut (Canon) on Jun 13, 2008 at 18:15 UTC

    You have to include the cookie in the response header, e.g. with $cgi->header( -cookie => $new_cookie_product )  (where $cgi is your CGI.pm or CGI::Simple object),  or $req->headers_out->add('Set-Cookie' => $new_cookie_product)  (where $req is your Apache/mod_perl request object).

    Update: use err_headers_out (as suggested by lihao) instead of headers_out, if you want to preserve the cookie on errors / internal redirects.

    ___

    P.S. please put <c> ... </c> tags around your code section   (this preserves indentation, handles PM-special characters like [] properly, etc...)

      Hello,
      I was including

      use CGI;
      my $query = new CGI();
      which I would use in the same example you gave me
      $query->headers_out->add('Set-Cookie' => $new_cookie_product)
      do I need to include the CGI:Simple?

        Calling headers_out on a CGI object won't work...  You didn't say whether you're using CGI-style scripts (via ModPerl::Registry) or the mod_perl API, so I mentioned both variants.  In the latter case, you don't need CGI (nor CGI::Simple), i.e. you'd simply call headers_out on the object provided by Apache2::RequestRec.

        Also see Generating HTTP Response Headers