1

I am seeing nothing wrong in my code below. However, when i run in my browswer, i get the error array to string conversion. What could i be missing in my code.

The error points to this line of code curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Thank you for your help

    $url = 'example.com/2394'
    $curlFile = curl_file_create($file);
    $data = [

       'msg_code' => '',
       'time' => ''
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    $result = json_decode($result, TRUE);
CodeNewbie
  • 49
  • 3
  • 11
  • 1
    `http_build_query($data)` is what you need. `CURLOPT_POSTFIELDS` expects a `* char` parameter for the data, IE: `foo=bar&bar=foo`. – Jaquarh Dec 31 '18 at 15:56
  • 6
    Possible duplicate of [curl POST format for CURLOPT\_POSTFIELDS](https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields) – Jaquarh Dec 31 '18 at 15:56
  • But from the docs regarding CURLOPT_POSTFIELDS, `this parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. ` So an array, should be fine? – Jonnix Dec 31 '18 at 16:02

1 Answers1

0

CURLOPT_POSTFILEDS requires an urlencoded string or an array as param. Read PHP Manual curl_setopt. Have changed your example, now it uses an urlencoded string.

change that code:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

to:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
ttrasn
  • 4,322
  • 4
  • 26
  • 43
  • 5
    Although this is correct, please refrain from answering duplicate questions that already have answers. This makes the original poster think to ask more off-topic questions in the future without researching prior. – Jaquarh Dec 31 '18 at 15:58
  • @Jaquarh yea sorry, I didn't see comments. but why downvote ? – ttrasn Dec 31 '18 at 16:13
  • 2
    @ttrasn Not my downvote, but answers on duplicate questions can be considered "not useful", which is probably what the downvote is for. The question already has a near identical answer to yours on https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields - there is no reason to have such a similar answer to the same question in a different place – GrumpyCrouton Dec 31 '18 at 16:20