Posting multidimensional array as multipart/form-data in curl php

  curl, multipartform-data, php

Similar questions ->

  1. How to upload files (multipart/form-data) with multidimensional POSTFIELDS using PHP and CURL?
  2. Posting multidimensional array with PHP and CURL

Before you report the question as duplicate please note those questions are 11 or more years old. And I am asking about the best way to do this.

The problem is the same though.

I have a multidimensional array that I need to post as multipart/form-data. All answers in those questions suggest that we will need to convert the post data to scalar values.

For eg.

## If this is the data that need to be posted
$postDataRaw =
    [
        'name' => 'abcd',
        'membership' =>
            [
                'stackoverflow',
                'serverfault',
                'webmasters']
    ];

## We convert it like this
$postDataPrepared = [
    'name' => 'abcd',
    'membership[0]' => 'stackoverflow',
    'membership[1]' => 'serverfault',
    'membership[2]' => 'webmasters'
];

Is this still the only way to accomplish this?

Also instead of complicated recursive functions can we simply use this

$postDataRaw =
    [
        'name' => 'abcd',
        'membership' =>
            [
                'stackoverflow',
                'serverfault',
                'webmasters']
    ];
$encoded = urldecode(http_build_query($postDataRaw));
$postDataManual = [];
array_map(function ($postFieldKeyValueString) use (& $postDataManual) {
    $keyValuePair = explode('=', $postFieldKeyValueString);
    $postDataManual[$keyValuePair[0]] = $keyValuePair[1];
}, explode('&', $encoded));

var_dump($postDataManual);

The result is what we expect

array (size=4)
  'name' => string 'abcd' (length=4)
  'membership[0]' => string 'stackoverflow' (length=13)
  'membership[1]' => string 'serverfault' (length=11)
  'membership[2]' => string 'webmasters' (length=10)

It relies on php’s http_build_query to add the key (if I may call it as such) for the nested arrays. What sort of problems am I expecting if I use this method? I mean is it consistent enough to use in production.

Source: Ask PHP

LEAVE A COMMENT