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

Hi,

I am trying to write a fairly complex spider which does a lot of client side parsing. I have to go through 3 pages, each page sets a different cookie and I am only allowed access when all three cookies are set.

I know how to parse HTML and get the next parameter set out. But, how do I add a new cookie manually to the cookie jar? In the actual app, this is done using Javascript, which I can't use with LWP, of course

For instance, I need to add a cookie with the following key value pair:
TR=xxxxxxxxxxxxxxxxxxxxxxxx (where the xxx represent a long session number which I've scraped from the previous page)

I define a cookie jar as a new instance of HTTP::Cookies. Using the perldoc, I see that I need to call "set_cookie" (with 6 parameters, most of which make no sense to me. I just want a key value pair to be set in the cookie. I tried adding the path and domain parameters, with no luck). This seems to silently fail, so I can't proceed any further. Does anyone have a snippet of code which manually adds a cookie t o a cookie jar that they'd not mind sharing ?

Thanks in advance

Replies are listed 'Best First'.
Re: Setting cookies manually
by Joost (Canon) on Jun 27, 2004 at 20:40 UTC
    This is all untested, so make of it what you will

    Most of the settings I gathered from the source of HTTP::Cookies, because the documentation on set_cookie is a bit too sparse.

    Anyway, setting discard to true seems to remove the cookie, setting path_spec seems to enable checking of the path, so I set it to 1 and the path to "/" to enable the cookies for the whole server, I set max_age to 0 (you might want to experiment with that), because we're talking about session cookies, and the version to 0 because I've never dealt with v2 cookies before. Default HTTP port is 80.

    I end up with this:

    $jar->set_cooke(0,"name","value","/","hostname",80,1,0,0,0);

    For a more extended introduction to cookies, take a look at the docs for CGI::Cookie.

    Good luck.
    Joost.