How do I POST an array with multipart/form-data encoding?
If you want an associated array you can pass index in a name of a form field:
Content-Type: multipart/form-data; boundary=--abc
--abc
Content-Disposition: form-data; name="name[first]"
first value
--abc
Content-Disposition: form-data; name="name[second]"
second value
Then on php level print_r($_POST) would give you
Array ( [name] => Array ( [first] => 'first value', [second] => 'second value' ) )
If you are after just a normal ordered array then same as you did:
Content-Type: multipart/form-data; boundary=--abc
--abc
Content-Disposition: form-data; name="name[]"
first index
--abc
Content-Disposition: form-data; name="name[]"
second index
Then on php level print_r($_POST) would give you
Array ( [name] => Array ( [0] => 'first index', [1] => 'second index' ) )
Params with [] in their names translating into arrays on a server side is a feature specific to PHP (http://www.php.net/manual/en/faq.html.php#faq.html.arrays).
As for multipart encoding you can find more in RFC: http://www.ietf.org/rfc/rfc1867.txt
DougW
Updated on July 09, 2022Comments
-
DougW almost 2 years
In a GET parameter string, or an "x-www-form-urlencoded" POST request, it's possible to specify an array of parameters by naming them with brackets (e.g. "name[]").
Is there a "correct" (or at least a wide-spread convention) way to specify an array of parameters with a "multipart/form-data" POST request?
Would the following be correct?
Content-Type: multipart/form-data; boundary=--abc --abc Content-Disposition: form-data; name="name[]" first index --abc Content-Disposition: form-data; name="name[]" second index
If it varies by platform, I'm interested in the convention for Apache/PHP.
-
DougW about 12 yearsThanks Alexei. Do you happen to have a reference to any spec or documentation that defines this? Specifically with regard to a multipart POST vs a standard urlencoded one?
-
Alexei Tenitski about 12 yearsI've added couple of links to the answer
-
DougW about 12 yearsI'm definitely being nit-picky here, but I do want to point out that the PHP docs only mention this convention with regard to web forms which always POST via x-www-form-urlencoded. I'm guessing that by the time POST variables get handed off from Apache to PHP that there is no distinction between content types, but I have not actually read anything that confirms that. And there are definitely a lot of seemingly safe assumptions about PHP that turn out to be disastrously incorrect. I'll make sure I verify this.
-
Aidan Do almost 2 yearsThis also works similarly for node.js express servers using multer. Though name[foo] will give you an object: { foo: 'value' }. Whereas name[] or name[0] will give you an array: [ 'value' ].