Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

Cookie設定をPerlで

PerlでCGIを作った時のCookie設定方法を調べてみた。
とりあえず複数ではなく、単体の値をセットする方法。

1.自力

まず、基本。べた書き。

sub set_cookie {

  my ($name, $value, $attr) = @_;
  # URLエンコード
  $value =~ s/(\W)/sprintf('%%%02X', unpack('C', $1))/eg;

  my $set_cookie;
  $set_cookie .= 'Set-Cookie:';
  $set_cookie .= "$name=$value; ";
  if ($attr->{path}) {    # pathが指定されていれば
    $set_cookie .= "path=$attr->{path}; ";
  }
  if ($attr->{domain}) {  # domainが指定されていれば
    $set_cookie .= "domain=$attr->{domain}; ";
  }
  if ($attr->{expires}) { # expiresが指定されていれば
    $set_cookie .= "expires=$attr->{expires}; ";
  }
  if ($attr->{secure}) {  # secure時のみ有効指定されていれば
    $set_cookie .= 'secure ';
  }
  $set_cookie .= "\n"; # 改行が最後に必要

  print $set_cookie;

}

set_cookie('id'=>'rightgo09', {'path'=>'/cgi-bin/test1/test2'});
#=> Set-Cookie:id=rightgo09; path=/cgi-bin/test1/test2;

2.モジュールを使う

2-1.CGI::Cookie.pmを使う

そのままなモジュール名のCGI::Cookieを使ってみる。

use CGI::Cookie;

sub set_cookie {

  my ($name, $value, $attr) = @_;

  my $set_ref = { '-name'  => $name,
                  '-value' => $value };
  if ($attr->{path}) {    # pathが指定されていれば
    $set_ref->{-path} = $attr->{path};
  }
  if ($attr->{domain}) {  # domainが指定されていれば
    $set_ref->{-domain} = $attr->{domain};
  }
  if ($attr->{expires}) { # expiresが指定されていれば
    $set_ref->{-expires} = $attr->{expires};
  }
  if ($attr->{secure}) {  # secure時のみ有効指定されていれば
    $set_ref->{-secure} = 1;
  }

  print 'Set-Cookie:', CGI::Cookie->new($set_ref), "\n";

}

set_cookie('id'=>'rightgo09', {'expires'=>'Thu, 26-Nov-2009 09:45:00 GMT'});
#=> Set-Cookie:id=rightgo09; path=/; expires=Thu, 26-Nov-2009 09:45:00 GMT


pathを指定しないとデフォルトでドキュメントルート直下になるらしい。

2-2.CGI.pmを使う

CGI.pmでも同じことが可能。

use CGI;

sub set_cookie {

  my ($name, $value, $attr) = @_;
  my $set_ref = { '-name'  => $name,
                  '-value' => $value };
  if ($attr->{path}) {    # pathが指定されていれば
    $set_ref->{-path} = $attr->{path};
  }
  if ($attr->{domain}) {  # domainが指定されていれば
    $set_ref->{-domain} = $attr->{domain};
  }
  if ($attr->{expires}) { # expiresが指定されていれば
    $set_ref->{-expires} = $attr->{expires};
  }
  if ($attr->{secure}) {  # secure時のみ有効指定されていれば
    $set_ref->{-secure} = 1;
  }

  print 'Set-Cookie:', CGI->new->cookie($set_ref), "\n";

}

set_cookie('id'=>'rightgo09', {'expires'=>'Thu, 26-Nov-2009 09:45:00 GMT',
                                'secure'=>1});
#=> Set-Cookie:id=rightgo09; path=/; expires=Thu, 26-Nov-2009 09:45:00 GMT; secure

今度は複数セットする方法を調べる。