in reply to Re^2: Can a cookie created via CGI.pm be deleted by CGI::SESSION?
in thread Can a cookie created via CGI.pm be deleted by CGI::SESSION?

CGI::Session::delete() really just does this:
my $cgi = CGI->new(); my $cookie = $cgi->cookie( -name=>$self->name, -value => 1, -expires=> + '-1d');
And then later it sends the header including this cookie definition back to the browser. (example later in this post)

The cookie isn't really managed by perl, it is managed by the browser. By telling the browser that the cookie was supposed to expire a day ago you can cause it to be deleted.

This is done with the http headers that you send back with your response.

It is easier to do this using one of the standard modules instead of writing the "Set-Cookie" header manually.

Basic Example:

my $cgi= CGI->new(); my $cookie = $cgi->cookie( -name=>$name, -value => 1, -expires=> '-1d' +); print $query->header(-cookie => $cookie, type => 'text/html'); print "This text is sent to the browser, and at the same time the cook +ie is cleared\n";
Note that this is setting what the value of the cookie will be -after- the browser gets this response.

If you want to remove the cookie for -this- invocation you could modify the value of $ENV{HTTP_COOKIE}. For example, this would remove all cookies for -this- run - but not future ones.

delete $ENV{HTTP_COOKIE};

I'm sure there is a module for modifying the current cookie definitions, but I can't think of one offhand and am too tired to search at the moment :)

Hope this helped.

Replies are listed 'Best First'.
Re^4: Can a cookie created via CGI.pm be deleted by CGI::SESSION?
by imp (Priest) on Jul 03, 2006 at 07:09 UTC
    Ok I couldn't resist looking for an existing solution - but didn't see one.

    You can do something like this though:

    # # Temporarily pretends a cookie does not exist by modifying # the HTTP_COOKIE env variable. # sub rm_cookie { my ($cgi,$name) = @_; my $raw = $cgi->raw_cookie; # Obtain a list of all cookies (they are ; separated) # But exclude the one with the name you specify my @cookies = grep {!/^$name=/} split /; ?/, $raw; # Replace the HTTP_COOKIE env variable with the new fake # set of cookies. This is important, you might not want to # hide all cookies - just this one. $ENV{HTTP_COOKIE} = join('; ',@cookies); }
    And then if you want to remove a cookie named 'foo':
    rm_cookie($cgi, 'foo');
    But keep in mind this is making perl pretend that there isn't a cookie by that name. You still need to remove the actual cookie (if this is your intent), using something similar to the parent post. Off to sleep - really this time.