Using Cookies with CGI.pm

Top Japanese page




Overview

Set or read Cookie using CGI.pm. When you do not want to use CGI.pm to handle Cookie, refer to Using Cookies without CGI.pm.

Flow

  1. Load CGI.pm
  2. Make an object of CGI
  3. Make a cookie format from the cookie method
  4. Delete path=
  5. Output to the http header
  6. When read, use the cookie method

A sample code

 use CGI;
 
 my $q = CGI->new;
 
 my $text = 'Cookie example';
 
 # Cookie setting
 my $cookie = $q->cookie(-name    => "mycookie",
                         -value   => "$text",
                         -expires => "+1y");
 $cookie = &cookie_path_fix($cookie);
 print $q->header(-type=>'text/html', -cookie=>"$cookie");
 
 # Cookie read back
 my $readcookie = $q->cookie("mycookie");
 
 sub cookie_path_fix {
     my $a = shift;
     $a =~ s/path\s*=\s*[^;]*;//i;
     return $a;
 }

Description of the code

 use CGI;

Load CGI.pm.

 my $q = CGI->new;

Make a CGI object.

 my $text = 'Cookie example';

In this example, save 'Cookie example' into cookie.

 # Cookie setting
 my $cookie = $q->cookie(-name    => "mycookie",
                         -value   => "$text",
                         -expires => "+1y");

Make a form of the cookie using the cookie method. -name is cookie name, -value is saving sentense, -expires is expiration period. -expires can take the following argumetns as examples.

        +30s                                30 seconds
        +10m                                10 minutes
        +1h                                 1 hour
        -1d                                 Yesterday(right now)
        now                                 Now
        +3M                                 3 monthe
        +10y                                10 years
        Thursday, 25-Apr-1999 00:40:33 GMT  The date specified
 $cookie = &cookie_path_fix($cookie);

Delete path= from the generated cookie form. The path should be in the form but it did not work well. cookie_path_fix routine will be explained later.

 print $q->header(-type=>'text/html', -cookie=>"$cookie");

Print out HTTP header wiht Set-Cookie. This is equivalent to the following lines.

 print "Set-Cookie: $cookie\n";
 print "Content-Type: text/html\n\n";
 # Cookie read
 my $readcookie = $q->cookie("mycookie");

When reading the cookie, use the cookie method. In this example, $readcookie contains 'Cookie example'. You can get the cookie value from $ENV{HTTP_COOKIE} alternatively.

 sub cookie_path_fix {
     my $a = shift;
     $a =~ s/path\s*=\s*[^;]*;//i;
     return $a;
 }

cookie_path_fix routhine. Simply remove path= path from the input argument.