Skip to content

Instantly share code, notes, and snippets.

@yisraeldov
Last active August 27, 2019 11:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yisraeldov/ec29d520062575c204be7ab71d3ecd2f to your computer and use it in GitHub Desktop.
Save yisraeldov/ec29d520062575c204be7ab71d3ecd2f to your computer and use it in GitHub Desktop.
create an array that can be passed to `CURLOPT_POSTFIELDS` that contains mutidimension arrays and `CURLFile`s
<?php
/**
* Use this to send data with multidimensional arrays and CURLFiles
* `curl_setopt($ch, CURLOPT_POSTFIELDS, build_post_fields($postfields));`
*
* @param $data
* @param string $existingKeys - will set the paramater name, probably don't want to use
* @param array $returnArray - Can pass data to start with, only put good data here
*
* @return array
* @author Yisrael Dov Lebow <lebow@lebowtech.com>
* @see https://stackoverflow.com/questions/3453353/how-to-upload-files-multipart-form-data-with-multidimensional-postfields-using
* @see http://stackoverflow.com/questions/35000754/array-2-string-conversion-while-using-curlopt-postfields/35002423#comment69460359_35002423
*/
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment