问题
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?
回答1:
The C implementation of curl_setopt doesn't seem to URL-encode the text. However, in PHP5, the http_build_query function returns a query string representation of the array that is URL-encoded.
Example Usage
$curl_parameters = array(
'param1' => $param1,
'param2' => $param2
);
$curl_options = array(
CURLOPT_URL => "http://localhost/service",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $curl_parameters ),
CURLOPT_HTTP_VERSION => 1.0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
curl_close( $curl );
回答2:
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
.
回答3:
One problem with using an array for CURLOPT_POSTFIELDS is that you can't have a name-value pair with an empty value.
回答4:
POST data is not added to the URL (like GET) so you don't need to URLencode it.
回答5:
I use:
curl_setopt($curl , CURLOPT_POSTFIELDS, $array );
instead of:
curl_setopt($curl , CURLOPT_POSTFIELDS, http_build_query($array) );
来源:https://stackoverflow.com/questions/574242/how-to-send-array-with-curl-should-i-urlencode-it