I cannot believe it! I’ve spent all day on this annoying little deficiency (of cURL php library) that wouldn’t let me POST multiple files to remote API.

Unsuspecting me was hauling this array (showing json below, I don’t like printing arrays) around and wondering why files were not saved on the remote server.

My curl method…

Well, can you guess what the problem is?

Even though php docs say that CURLOPT_POSTFIELDS supports arrays, don’t believe it, it doesn’t really… well it accepts simple array key=>value pairs, but not multidimensional arrays!

So array above will spit out following: Array to string conversion exception.

So how do I submit multiple photos to API which expects photos[] ?

Firs thing that came to mind is of course: http_build_query(query_data)

Horrible idea!!

Because when you use string in CURLOPT_POSTFIELDS content type is set to Content-Type: application/x-www-form-urlencoded and no files are actually sent to API!

So dilemma: string -> cannot send file but can have photos[]; array -> can send 1 file but cannot have photos[]. What the hell right? How come no one thought of this?

My solution is a bit of a hack, and only works if you have php on the receiving end. Instead of generating a multidimensional array, we create simple key=>value pairs of photos.

Notice this last part $car[ "photos[ $k ]" ]

This generates following 1 dimensional array that curl can accept!

On the server php, receives this as "photos":{"0 ":{},"1 ":{},"2 ":{}}

Files are sent with correct content type and there is peace in the world again.

Leave a Reply

Your email address will not be published. Required fields are marked *