Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

php - POSTing Form Fields with same Name Attribute

If you have a form containing text inputs with duplicate name attributes, and the form is posted, will you still be able to obtain the values of all fields from the $_POST array in PHP?

question from:https://stackoverflow.com/questions/2203430/posting-form-fields-with-same-name-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. Only the last input element will be available.

If you want multiple inputs with the same name use name="foo[]" for the input name attribute. $_POST will then contain an array for foo with all values from the input elements.

<form method="post">
    <input name="a[]" value="foo"/>
    <input name="a[]" value="bar"/>
    <input name="a[]" value="baz"/>
    <input type="submit" />
</form>

See the HTML reference at Sitepoint.

The reason why $_POST will only contain the last value if you don't use [] is because PHP will basically just explode and foreach over the raw query string to populate $_POST. When it encounters a name/value pair that already exists, it will overwrite the previous one.

However, you can still access the raw query string like this:

$rawQueryString = file_get_contents('php://input'))

Assuming you have a form like this:

<form method="post">
    <input type="hidden" name="a" value="foo"/>
    <input type="hidden" name="a" value="bar"/>
    <input type="hidden" name="a" value="baz"/>
    <input type="submit" />
</form>

the $rawQueryString will then contain a=foo&a=bar&a=baz.

You can then use your own logic to parse this into an array. A naive approach would be

$post = array();
foreach (explode('&', file_get_contents('php://input')) as $keyValuePair) {
    list($key, $value) = explode('=', $keyValuePair);
    $post[$key][] = $value;
}

which would then give you an array of arrays for each name in the query string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...