0

Please tell me how to transfer a file using curl post without php warning that $ data_curl is an array PHP Notice: Array to string conversion...

$data_curl = array('domain' => $domain, 'token' => '*', 'files' => array());
foreach ($_FILES["files"]["tmp_name"] as $file) {
   $tmpfile = $_FILES['files']['tmp_name'][$i];
   $filename = $name_file."_".time().".".$type;
   $data_curl = $data_curl + array(
      'file'.$i => curl_file_create($tmpfile, $_FILES['files']['type'][$i], $filename)
   );
   $i++;    
} 
$ch = curl_init('https://google.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_curl);
curl_exec($ch);

json_encode and http_build_query do not send file.

Vector
  • 109
  • 5
  • Change `content-type` to `multipart/form-data` – nice_dev Apr 05 '21 at 15:08
  • 1
    Learned something new then. If only we had the ACTUAL error message instead of a cropped one – hppycoder Apr 05 '21 at 15:13
  • @hppycoder I agree. The OP needs to show on which line the error is coming and what's inside those inputs from the user. – nice_dev Apr 05 '21 at 15:16
  • @hppycoder error in this line `curl_setopt($ch, CURLOPT_POSTFIELDS, $data_curl);` – Vector Apr 05 '21 at 15:18
  • @Vector Did the header change fix the issue? – nice_dev Apr 05 '21 at 15:22
  • So it's similar to this post then - https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields – hppycoder Apr 05 '21 at 15:23
  • @hppycoder If you might have noticed, I also send files. These are not the same questions. – Vector Apr 05 '21 at 15:24
  • @nice_dev I changed it, the warning remained. – Vector Apr 05 '21 at 15:25
  • If you didn't notice the first answer with 100+ votes says: `In case you are sending a string, urlencode() it. Otherwise if array, it should be key=>value paired and the Content-type header is automatically set to multipart/form-data.` which is what @nice_dev has bene saying. Remove the Content-Type all together and send the array – hppycoder Apr 05 '21 at 15:26

1 Answers1

1

The reason why error pops up is because you have

$data_curl = array('files' => array());

The values cannot be arrays in themselves and rather just a string or an integer or floats or booleans with an exception of CURLFile objects .

Also, there is no point in sending files key as a POST param with no value inside it. So you could better remove it completely and just keep $data_curl = array();

nice_dev
  • 17,053
  • 2
  • 21
  • 35