Hi there and thanks for reading.
I'm trying to send data to an API in PHP, everything goes fine but mixin multidimensional arrays and files in the request.
Let's say I have this data:
$data = [
'option1' => 'Whatever',
'my_arr' => [
'key1' => 'xxx',
'key2' => 'yyy'
],
'file' => new CURLFile('/image/path/img.jpg', 'image/jpeg', 'img.jpg');
];
I send the data with this function:
protected function fetchUrl($url, $postParams, $headers = null, $method = 'post', $referer = 'https://www.google.com/', $userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0')
{
$methodLower = strtolower($method);
$handler = curl_init();
curl_setopt($handler, CURLOPT_URL, $url);
if ($methodLower === 'get')
curl_setopt($handler, CURLOPT_HTTPGET, true);
else if ($methodLower === 'post' || $methodLower === 'put') {
curl_setopt($handler, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if ($methodLower === 'post')
curl_setopt($handler, CURLOPT_POST, true);
curl_setopt($handler, CURLOPT_POSTFIELDS, http_build_query($postParams));
}
if (!empty($userAgent))
curl_setopt($handler, CURLOPT_USERAGENT, $userAgent);
if ($headers && count($headers) > 0)
curl_setopt($handler, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($handler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handler, CURLOPT_REFERER, $referer);
$body = curl_exec($handler);
$httpCode = curl_getinfo($handler, CURLINFO_HTTP_CODE);
if (false === $body)
error_log(sprintf('FETCH URL ERROR, CODE: %d; MSG: %s, URL: %s', $httpCode, curl_error($handler), $url));
curl_close($handler);
if (is_string($body))
return json_decode($body, JSON_OBJECT_AS_ARRAY);
return $body;
}
If I wrapp my array with http_build_query my files stop being sent as $_FILE and are transformed to a regular array, If I don't, my multidimensional array can't be sent 'cause curl just accept simple arrays.
So how can I send all data toguether?
Thanks in advance.