views:

1641

answers:

4

When I assign an array of data to be POSTed as a cURL option (via CURLOPT_POSTFIELDS), do I need to urlencode that data first or will that be taken care of?

+6  A: 

I can't seem to find any relevant info on curl_setopt urlencoding of Array values (if an Array is passed).

However if you're using PHP5, you can use the http_build_query function which automatically returns a query string representation of the Array (encoded and all).

$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

EDIT Looking at the C implementation of curl_setopt here at line 847, there doesn't seem to be any urlencoding, just simple string conversion.

Luca Matteis
It only says anything about the urlencoded part if your passing a string of data, nothing about if you need to preencode an array.
Uberfuzzy
+7  A: 

You don't have to urlencode first. However, it is important to realize that passing an array will make cURL send it as multipart/form-data, which explains why it is does not need to get urlencoded (by neither you nor cURL), and you need to use an array if you want to upload files. If you http_build_query() first (and send it as a string) it will be treated as application/x-www-form-urlencoded.

Patrick Daryll Glandien
Where did you read about urlencoding for arrays?
Luca Matteis
It does not urlencode them, there is no need to since it is getting sent as multipart form.
Patrick Daryll Glandien
I know that, but the spec doesn't say anything about generating an `multipart/form-data` if an Array is passed.
Luca Matteis
That's right, the documentation is slacky. I had to figure it out by myself by sniffing the packets and I think it's also somewhere in the comments (@the PHP doc). Since you have to pass an array if you want to upload files, multipart is the only way anyway.
Patrick Daryll Glandien
ok I guess I'll trust you since I can't test this. +1
Luca Matteis
Patrick is right.
Alix Axel
A: 

POST data is not added to the URL (like GET) so you don't need to URLencode it.

Chris Bartow
wrong, if passed as a string to the curl_setopt function, it needs to be encoded.
Luca Matteis
A: 

One problem with using an array for CURLOPT_POSTFIELDS is that you can't have a name-value pair with an empty value.

Really? You can't? Where have you read this?
Alix Axel