提交表单时从 URL 中删除 %5B%5D

2022-01-04 00:00:00 forms php html rewrite

当我提交一个包含多个同名复选框的表单时,我得到一个如下所示的 URL:www.mysite.com/search.php?myvalue%5B%5D=value1&myvalue%5B%5D=value2

When I submit a form with multiple checkboxes that have the same name I get a URL that looks something like this: www.mysite.com/search.php?myvalue%5B%5D=value1&myvalue%5B%5D=value2

有什么办法可以删除 %5B%5D 以使 URL漂亮",例如 htaccess?

Is there someway that I can remove the %5B%5D to make the URL "pretty", with something like htaccess?

代码:

<form>
     <input type="checkbox" name="myvalue[]" value="value1">
     <input type="checkbox" name="myvalue[]" value="value2">
</form>

推荐答案

有什么办法可以删除 %5B%5D 以使 URL漂亮",例如 htaccess?

没有.[] 是 URL 中的保留字符,因此它们绝对需要URL 编码.

No. The [] are reserved characters in URLs, so they definitely need to be URL-encoded.

如果使用 POST 不是一个选项,考虑到它是一个搜索表单,这是有道理的,最好的办法是给它们每个一个不同的名称,值为 1 左右.

If using POST is not an option, which makes sense given that it's a search form, your best bet is to just give them each a different name with a value of 1 or so.

<form>
    <input type="checkbox" name="option1" value="1" />
    <input type="checkbox" name="option2" value="1" />
</form>

或者,如果你真的坚持它们具有相同的名称,那么你应该自己提取查询字符串,而不是依赖 PHP 特定的特性,即在获取带有 [] 的参数时返回一个数组代码>名称中的后缀.

Or, if you really insist in them having the same name, then you should be extracting the query string yourself instead of relying on the PHP specific feature of returning an array when obtaining a parameter with a [] suffix in the name.

$params = explode('&', $_SERVER['QUERY_STRING']);

foreach ($params as $param) {
    $name_value = explode('=', $param);
    $name = $name_value[0];
    $value = $name_value[1];
    // ... Collect them yourself.
}

这样您就可以继续使用不带括号的名称.

This way you can just keep using the braceless name.

<form>
    <input type="checkbox" name="option" value="option1" />
    <input type="checkbox" name="option" value="option2" />
</form>

相关文章