包含方括号的表单输入字段名称,如 field[index] [英] Form input field names containing square brackets like field[index]

查看:31
本文介绍了包含方括号的表单输入字段名称,如 field[index]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多处理表单输入的 PHP 代码,其中输入字段名称包含方括号.我知道当 PHP 脚本检查 $_POST 变量时,这会以某种方式导致 PHP 数组.

I've seen a lot of PHP code that handles form input in which the input field names contain square brackets. I understand that this somehow results in PHP arrays when a PHP script examines the $_POST variable.

示例 HTML:

<form action='http://zzz.com' method='post'>
    <input name='fruit[1]' value='apple' />
    <input name='fruit[2]' value='banana' />
</form>

示例网址:

http://zzz.com?fruit[1]=apple&fruit[2]=banana

示例 PHP:

assert($_POST['fruit'] === array(1=>'apple', 2=>'banana'));

我的问题:

  • 背后的机制是什么?这些包含括号的名称在什么时候被转换为数组?这是 HTTP 协议的特性吗?网络服务器?PHP 语言?

  • What is the mechanism behind it? At what point do these names that contain brackets get converted into arrays? Is this a feature of the HTTP protocol? Of web servers? Of the PHP language?

继续上一个问题,这是常用的hack还是普通的编程工具?

Continuing the previous question, is this a commonly used hack or a normal programming tool?

在输入字段名称中使用括号的(所有)规则是什么?

What are (all) the rules for using brackets in input field names?

可以这样创建多维数组吗?

Can multidimensional arrays be created this way?

推荐答案

背后的机制是什么?其中点这个名字只包含括号转换为数组?是这是 HTPP 协议的一个特性吗?网络服务器?PHP语言?>

What is the mechanism behind? At which point this names that merely contain brackets are converted to arrays? Is this a feature of the HTPP protocol? Of web servers? Of the PHP language?>

这是 PHP 语言的一个特性.事实上,HTTP 协议并不禁止使用多个相同的 GET/POST 参数.根据 HTTP 规范,以下内容:

This is a feature of the PHP language. In fact, the HTTP protocol does not forbid the use of multiple identical GET/POST parameters. According to the HTTP spec, the following:

foo=bar&foo=baz

不应导致 foo == baz.这是具有两个不同值的两个参数.然而,PHP 会用最新的覆盖之前的 foo,导致 $_POST['foo'] == 'baz',即使它们可以被单独解析.

Should not result in foo == baz. These are two parameters with two different values. However, PHP will overwrite the former foo with the latest, resulting in $_POST['foo'] == 'baz', even if they could be parsed separately.

继续上一个问题,是这是一个常用的黑客或正常编程工具?

Continuing the previous question, is this a commonly used hack or a normal programming tool?

这取决于观点.在 PHP 世界中,这是完全正常的,因为该语言不支持在不使用括号 [] 的情况下指定多个同名参数.但在 HTTP 世界中,foo != foo[].

It depends on the point of view. In the PHP world, it is completely normal, as the language does not support the specification of multiple parameters of the same name without using the brackets []. In the HTTP world though, foo != foo[].

使用的(全部)规则是什么输入字段名称中的括号?

What are (all) the rules of using brackets in input field names?

与 PHP 数组相同,不同之处在于您不必引用字符串键.

The same as PHP arrays, except that you don't have to quote string keys.

可以创建多维数组吗这样?

Can multidimensional arrays be created this way?

是的,你可以.

这篇关于包含方括号的表单输入字段名称,如 field[index]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆