0

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.

Johnny
  • 1
  • 1
  • You can't use `http_build_query()` if you have file uploads. Just pass the `$data` array as `CURLOPT_POSTFIELDS` and it will do the right thing. – Barmar Jan 12 '22 at 20:25
  • Thanks for the response but nope, It will fail with 'my_arr' param as is second array dimension – Johnny Jan 12 '22 at 20:29

0 Answers0