【问题标题】:URL encode using html forms使用 html 表单的 URL 编码
【发布时间】:2012-01-30 14:39:29
【问题描述】:

如何对包含 Unicode 的 URL 进行编码?我想将它传递给命令行实用程序,我需要先对其进行编码。

<form action="index.php" method="get" >
<input type="text" name="find" value="عربي" /><br />
<input type="submit" value="search" />
<form />

示例: http://localhost/index.php?find=عربي

变成http://localhost/index.php?find=%DA%D1%C8%ED

【问题讨论】:

  • 所以你想عربي作为参数值却不知道怎么转换成%DA%D1%C8%ED,对吧?
  • 为什么不使用 POST? POST 请求将正确编码。
  • @e-zinc 所以你想告诉那些不使用完全由 ASCII 字符集描述的语言的人,他们不应该使用 GET?
  • @rdlowrey 我只想说,如果服务器端允许 POST,POST 的使用会更容易。

标签: php html url character-encoding


【解决方案1】:
$ cat testme
#!/usr/local/bin/php
<?php

$chars = array( "d8", "b9", "d8", "b1", "d8", "a8", "d9", "8a" );

foreach ($chars as $one) {
    $string .= sprintf("%c", hexdec($one));
}

print "String: " . $string . "\n";
print "Encoded: " . urlencode($string) . "\n";

?>
$ ./testme
String: عربي
Encoded: %D8%B9%D8%B1%D8%A8%D9%8A
$ 

【讨论】:

    【解决方案2】:

    %DA%D1%C8%ED不是Unicode序列,而是其他编码的URL编码序列。 URL 编码后 Unicode 中的عربي 应变为%D8%B9%D8%B1%D8%A8%D9%8A

    如果你想用 Unicode 字符构造有效的 URL,你可以使用类似的东西:

    $url = 'http://localhost/index.php?find=عربي';
    
    $url_parts = parse_url($url);
    $query_parts = array();
    parse_str($url_parts['query'], $query_parts);
    $query = http_build_query(array_map('rawurlencode', $query_parts));
    
    $url_parts['query'] = $query;
    $encoded_url = http_build_url($url_parts);
    

    注意:这只会对 URL 的 query 部分进行编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 2010-12-21
      • 2010-11-01
      相关资源
      最近更新 更多