http://www.perlmonks.org?node_id=836283

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

Hello Monks, I am have some very simple code that is completely baffling me. I have an HTML file that sets cookies. I have another html file that displays the cookies perfectly. I have also written a simple Perl script that does not show the cookies consistently. I have listed each piece of code below:

Set the cookie - works as expected:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HEAD> <TITLE>Test</TITLE> <script type='text/Javascript'> document.cookie="ff=1;"; document.cookie="gg=;"; </script> </HEAD> <BODY> Cookie Set </BODY> </HTML>
Show the cookie with HTML - works as expected:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> Test </TITLE> </HEAD> <BODY> <script type='text/Javascript'> alert(document.cookie); </script> </BODY> </HTML>
Show the cookie with Perl - only works if cookie is empty
#!/usr/bin/perl use CGI::Cookie; %cookies = fetch CGI::Cookie(); $ctab .= "<table border=1>"; $ctab .= "<tr><td>Name</td><td>Value</td></tr>\n"; foreach $c (keys %cookies) { $v = $cookies{$c} -> value(); $ctab .= "<tr><td>$c</td><td>$v</td></tr>\n"; } $ctab .= "</table><BR><BR>"; print "Content-type: text/html\n\n"; print $ctab;
I have tried this on a few servers.

One: Free BSD / Apache 1.3.41 / Perl 5.6.1 shows both cookies with Perl and both with html.

Two: Red Hat ES 4 / Apache 2.0.52 / Perl 5.8.5 shows no cookies with Perl script and both with html.

Three: Red Hat 5.3 / Apache 2.2.3 / Perl 5.8.8 shows only empty cookies (gg) with Perl and both with html.

I have no idea why javascript shows the cookies are there and Perl does not recognize them. Any help would be greatly appreciated. Thank You.

Replies are listed 'Best First'.
Re: Problems reading ALL cookies
by ahmad (Hermit) on Apr 22, 2010 at 18:41 UTC

    I have tested it on windows, and it does show both gg & ff

    Here's the output:

    NameValue
    gg
    ff1


    I think you should set the cookie domain using javascript not only the key=>value pair

Re: Problems reading ALL cookies
by ig (Vicar) on Apr 22, 2010 at 19:23 UTC

    What is the value of $ENV{HTTP_COOKIE} in your CGI script?

      $ENV{HTTP_COOKIE} is gg=

      So It looks like I need to understand why the HTTP header is different when accessing an HTML page than it would be accessing a Perl page.

        I would next try a network sniffer (wireshark works for me) to inspect the HTTP traffic between the browser and web server. If the cookie is complete in the HTTP traffic, then you have an issue in your web server. If not, then you have an issue in your browser.

Re: Problems reading ALL cookies
by AR (Friar) on Apr 22, 2010 at 19:27 UTC
    I highly recommend you use warnings; and use strict; in all of your scripts, no matter how short.