【问题标题】:Why CGI.pm does not handle UTF-8 properly when dealing with "application/x-www-form-urlencoded" forms?为什么 CGI.pm 在处理“application/x-www-form-urlencoded”表单时不能正确处理 UTF-8?
【发布时间】:2013-09-12 18:52:53
【问题描述】:

我昨天升级了 Debian stable 并使用“新”Perl 5.14 我也获得了“新”CGI 模块(v3.52)。我认为以前的版本是 3.43。升级破坏了我的旧网络表单,我发现来自 enctype "application/x-www-form-urlencoded" 表单字段的 UTF-8 字符被解码两次。虽然使用 enctype "multipart/form-data" 一切正常。

问题:

  • 为什么不能正确处理带有“application/x-www-form-urlencoded”的表单中的 UTF-8?它们仍应正确解码,即使“multipart/form-data”可能更适合处理二进制数据。

这是解决解码问题的小测试用例:

#!/usr/bin/perl

use strict;
use warnings;
use utf8::all;
use CGI qw(:all -utf8);

my $q = new CGI;

sub build_form {
  return q|
  <form method="post" enctype="application/x-www-form-urlencoded">
  <br />
  Y: <input type="text" name="y" />
  </form>|;
}

print $q->header( -type=>"text/html; charset=utf-8", ),
  $q->start_html( -title=>"test", -encoding=>"utf-8" ),
  $q->h1(  $q->param(  'x' ) . " " ),
  $q->start_form(),
  "X: ",
  $q->textfield( -name=>'x' ), 
  $q->end_form(), "\n\n", 
  $q->br(),
  $q->h1( $q->param( 'y' ) . " " ),
  build_form(),
  $q->end_html;

PS。我不认为升级破坏了 UTF-8 解码。似乎升级后自动生成的表单的编码类型错误(“application/x-www-form-urlencoded”),因为使用了已弃用的辅助方法(例如startform 而不是start_form)。

【问题讨论】:

  • 定义“处理不当”?你的脚本很适合我。
  • @ikegami:如果我在两个表单字段中输入“õ”,提交 X 会返回“õ”,Y 会返回“Ãμ”。最后一个是双重解码的结果,AFAIU。

标签: perl utf-8 cgi


【解决方案1】:
use utf8::all;

binmode(STDIN, ':encoding(UTF-8)');

这会破坏浏览器发送的数据。跟进

binmode(STDIN);

撤消更改并防止损坏。

【讨论】:

  • 你有解释吗,为什么一个表单 enctype 受到影响而另一个不受影响?
  • 因为 õ 在解码时显示为它的 UTF-8 编码,而另一个显示为它的 URI 编码。
猜你喜欢
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 2022-01-19
  • 2016-02-21
  • 2020-04-13
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多