フォーム入力内容をクッキーに保存
#! /usr/local/bin/perl $COOKIENAME = "formdata"; # クッキー名 $COOKIELIFE = 30; # クッキー保存日数 print qq(Content-type: text/html; charset=Shift_JIS\n\n); loadForm(); # フォームデータ取込 if($FORM{'text'}) { printCookie(); # クッキーデータ保存 } else { loadCookie(); # クッキーデータ取込 } printPage(); exit; #====================================================================HTML出力 sub printPage { print <<" END"; <html> <head> <title>フォーム入力内容をクッキーに保存</title> </head> <body> <form action="$ENV{'SCRIPT_NAME'}" method="post"> 名前:<br><input type="text" name="name" size="100" value="$COOKIE{'name'}"><br><br> メール:<br><input type="text" name="mail" size="100" value="$COOKIE{'mail'}"><br><br> 本文:<br><textarea name="text" cols="70" rows="10"></textarea><br><br> <input type="submit" value=" 送 信 "><br> <small>※名前・メールは一度送信すると次回から自動的に入力されます。</small> </form> END foreach $key (keys %FORM) { print qq($key:$FORM{$key}<br>\n); } print <<" END"; </body> </html> END } #====================================================================クッキーデータ保存 sub printCookie { my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my @wdy = qw(Sun Mon Tue Wed Thu Fri Sat); my ($sec, $min, $hour, $day, $mon, $year, $wday) = gmtime(time + $COOKIELIFE * 24 * 60 * 60); my $expires = sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT", $wdy[$wday], $day, $mon[$mon], $year + 1900, $hour, $min, $sec); print qq(Set-Cookie: $COOKIENAME=$COOKIE; expires=$expires;\n); } #====================================================================クッキーデータ取込 sub loadCookie { my ($pair, $cpair); foreach $pair (split(/;\s*/, $ENV{'HTTP_COOKIE'})) { my ($name, $cookie) = split(/=/, $pair); if($name eq $COOKIENAME) { foreach $cpair (split(/&/, $cookie)) { my ($key, $value) = split(/#/, $cpair); $value =~ tr/+/ /; $value =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg; $COOKIE{$key} = $value; } last; } } } #====================================================================フォームデータ取込 sub loadForm { my ($query, $pair); if($ENV{'REQUEST_METHOD'} eq 'POST') { read(STDIN, $query, $ENV{'CONTENT_LENGTH'}); } else { $query = $ENV{'QUERY_STRING'}; } foreach $pair (split(/&/, $query)) { my ($key, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg; $COOKIE{$key} = $value; $value =~ s/&/&/g; $value =~ s/</</g; $value =~ s/>/>/g; $value =~ s/\x0D\x0A/<br>/g; $FORM{$key} = $value; } $COOKIE = $query; $COOKIE =~ s/=/#/g; }
〔 実行する 〕