http://qs321.pair.com?node_id=142305

cLive ;-) has asked for the wisdom of the Perl Monks concerning the following question: (cgi programming)

<question type="common">
I use CGI.pm to set my cookie, but when I try to read it, it's not there.

What gives?
</question>

Originally posted as a Categorized Question.

  • Comment on Why can't I access a cookie I have set?

Replies are listed 'Best First'.
Re: Why can't I access a cookie I have set?
by cLive ;-) (Prior) on Jan 29, 2002 at 10:19 UTC
    Let's assume you have a CGI object:
    my $q = new CGI;
    Cookies are accessed through $q->cookie('name').

    Cookies are sent by the browser when requesting the page. If you set a cookie in a CGI script, the cookie is sent to the browser, but not set in $q->cookie. ie,

    Set == Cookie stored in browser Readable == Cookie available in $q->cookie('name') Event Set? Readable? Browser request n n Response to Browser y n Subsequent Browser y y Requests(*)

    (*) - within the life of the cookie.

    Just remember that $q->cookie only contains cookies sent by the browser as part of that particular http request!

    Hope that clears things up a little :)

    cLive ;-)

Re: Why can't I access a cookie I have set?
by simon.proctor (Vicar) on Jan 31, 2002 at 23:33 UTC
    Referring to the CGI documentation, the following example is presented.
    $cookie = $query->cookie(-name=>'sessionID', -value=>'xyzzy', -expires=>'+1h', -path=>'/cgi-bin/database', -domain=>'.capricorn.org', -secure=>1); print $query->header(-cookie=>$cookie);

    I would recommend that you read the pod for CGIand use the code presented there. As a pointer, I would stick to the CGI module and not use CGI::Cookie. I say this as I've had no end of problems with CGI::Cookie in the past that disappeared once CGI was used instead.

    Note that the code example assumes you have already created a CGI query object.

    Hope that helps.
      Although your answer correctly states how to set a cookie, that was not the point I was trying to make. Several people asked why they couldn't read a cookie when they had just set it. ie, they wanted to read the cookie in the same invocation of their script.

      That was why I posted this question and answer combo.

      cLive ;-)