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

前端 未结 3 774
小蘑菇
小蘑菇 2021-01-12 13:41

I\'m having problems with posting a multidimensional array with file uploads using PHP and CURL.

The multidimensional array is for example:

$post[\'q         


        
相关标签:
3条回答
  • 2021-01-12 14:00

    Another way to accomplish the first answer:

    foreach( array("yes","no","maybe") as $key=>$value )
        $post["answers[$key]"] = $value;
    0 讨论(0)
  • 2021-01-12 14:20

    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.

    0 讨论(0)
  • 2021-01-12 14:21

    Try this recursive function.

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

    <?php
    function 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));
    
    0 讨论(0)
提交回复
热议问题