How to upload files (multipart/form-data) with multidimensional POSTFIELDS using PHP and CURL? How to upload files (multipart/form-data) with multidimensional POSTFIELDS using PHP and CURL? curl curl

How to upload files (multipart/form-data) with multidimensional POSTFIELDS using PHP and CURL?


multipart/form-data doesn't support nested values. And I don't believe CURL can do it either.

I suspect the receiving end of your request is also a PHP script. If, then you can submit a nested array as one of the values, if you just prepare it yourself:

 $post['answers[0]'] = "yes"; $post['answers[1]'] = "no"; $post['answers[2]'] = "maybe";

Theoretically you'd just need 'answers[]' without the index, but that would overwrite the preceeding value - and thus only works with http_build_query.

I'm not sure if there is any HTTP library in PHP which can do this automatically.


Another way to accomplish the first answer:

foreach( array("yes","no","maybe") as $key=>$value )    $post["answers[$key]"] = $value;


Try this recursive function.

https://gist.github.com/yisraeldov/ec29d520062575c204be7ab71d3ecd2f

<?phpfunction build_post_fields( $data,$existingKeys='',&$returnArray=[]){    if(($data instanceof CURLFile) or !(is_array($data) or is_object($data))){        $returnArray[$existingKeys]=$data;        return $returnArray;    }    else{        foreach ($data as $key => $item) {            build_post_fields($item,$existingKeys?$existingKeys."[$key]":$key,$returnArray);        }        return $returnArray;    }}

And you can use it like this.

curl_setopt($ch, CURLOPT_POSTFIELDS, build_post_fields($postfields));