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

Is it possible to convert cookies, comming in from a CGI request and send them to a "$cookie_jar style" so they can be used in a LWP request???
And of course, is it also possible to do the reverse -->> from LWP to CGI???
Any, monk some knowledge about that :-)

Replies are listed 'Best First'.
Re: Cookies from CGI to LWP and back
by Corion (Patriarch) on Apr 14, 2004 at 11:23 UTC

    Sure this is possible. You might want to look at how HTTP::Proxy does it, or look at the LWP::UserAgent documentation.

    You don't even need to use a file, you can set the cookie headers in your UserAgent cookie jar object directly from the headers received in your CGI.

      Hi,
      Thanxs for the response, but I do not understand...
      HTTP::Proxy is an LWP based daemon doing LWP requests

      I want to transfer a CGI request to an LWP request, cookies and values should be maintained if possible. For the variables this is no problem, but the cookies need to be retrieved out of the CGI object and stored in an HTTP::Cookie object. I do not find an easy way to get them out of the CGI and store them in this HTTP::Cookie object.
      The reverse process should also be possible.

      my $ua = LWP::UserAgent->new;
      my $cookie_jar = new HTTP::Cookies;
      my %cookies = fetch CGI::Cookie;
      $cookie_jar->extract_cookies(%cookies);
      $ua->cookie_jar($cookie_jar);
      my $response = $ua->get(http://someserver/somepage.cgi);

      The above does not work.

      Any idea?????

      greetings
      Tom

        You don't tell me in what way it does not work. My mindreading capabilities are limited in range, and I'm currently busy influencing important worldwide decisions, so please excuse me that I don't snoop through your brain to find out the exact "not working" you mean.

        The HTTP::Cookies documentation tells me that you should use its extract_cookies method on the text of the response and not on some hash you retrieved elsewhere.

        So you will either have to craft a HTTP::Response out of your incoming CGI request, or manually transfer each cookie out of the hash you already have:

        foreach $cookie (keys %cookies) { # $cookie_jar->set_cookie($version, $key, $val, $path, $domain, $port, # $path_spec, $secure, $maxage, $discard, \%rest) $cookie_jar->set_cookie(1, $cookie->name,$cookie->value,$cookie->path,$cookie->domain, 80,'',0,$cookie->expires,0,{}); };

        I haven't tested that code, but it comes more or less directly from the documentation of CGI::Cookie and HTTP::Cookie. Also, again, look at how HTTP::Proxy does its thing. It does something quite similar to what you do, if you look closer at it.