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

I have a simple block of code and I am trying to set and retrieve a session cookie. It works like a charm when I put in an expiration date, but I don't want and expiration date, I want it to stay as long as the browser is open and then go away when the browser closes. I took most of this code straight out of the question and answers section. Am I mising something?
$q = new CGI; my $cookievalue = $q->cookie('User_Session'); print "Content-type: text/html\n\n"; $initcookie = $q->cookie( -name=>'User_Session', -value=>'abc', -expires=>'', # leave this blank -path=>'/', -domain=>'www.thedialogcenter.com', -secure=>0 ); print "The cookie value is : $cookievalue<br>";
My hope is to have no cookie value show up the first time through. I then wish to refresh the page (to simulate another page calling it) and have it show up. This is just a simple test before I put the logic into my existing scripts. Any help would be much apprciated. Thanks

Replies are listed 'Best First'.
Re: Problem retrieving session cookies
by jasonk (Parson) on Apr 10, 2003 at 02:58 UTC

    CGI passes this information to CGI::Cookie, which includes an expiration if -expires is defined, since an empty value is defined, you get an expiration date. Instead of passing an empty value, just leave that line out altogether:

    $initcookie = $q->cookie( -name=>'User_Session', -value=>'abc', -path=>'/', -domain=>'www.thedialogcenter.com', -secure=>0 );

    We're not surrounded, we're in a target-rich environment!
      Thanks for the advice. I tried to just remove it and it did not seem to make a difference. Still when I try to grab the value of the cookie and print it out, I don't get anything. I added the following print statement print $q->header(-cookie=>$initcookie); and what follows is the result (I'm guessing it is not actually printing what is in the cookie, but rather what I am trying to put in the cookie)
      Set-Cookie: User_Session=abc; domain=www.thedialogcenter.com; path=/ Date: Thu, 10 Apr 2003 03:11:44 GMT Content-Type: text/html; charset=ISO-8859-1
        No - that is the cookie it's printing. Remember that a cookie is simply another HTTP header line printed by your script -in the example code you posted, you weren't actually printing the cookie anywhere. As jasonk says, you should be able to just print the cookie with *no* expiry date defined and it automatically becomes a session cookie.

        Cheers,
        Ben