Posting an array with curl_setopt

2019-06-14 23:27发布

问题:

The attached code is returning "Notice: Array to string conversion in...". Simply my array is being handled to the remote server as a string containing "Array" word. the rest of the variables are fine.

How can I pass my array $anarray without this problem?

<?php

$data = array(
    'anarray' => $anarray,
    'var1' => $var1,
    'var2' => $var2
 );

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "MY_URL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);

?>

回答1:

Use http_build_query()

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// The values of variables will be shown but since we don't have them this is what we get

You can then access it normally using the $_POST superglobal



回答2:

The best way to accomplish what you're after is to use http_build_query().



回答3:

From http://www.php.net/manual/en/function.curl-setopt.php description of CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. 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. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.



回答4:

Due to the nature of the HTTP protocol, and the way curl_setopt function works, $anarray cannot be passed directly as an array.

The following statement:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

takes an array of POST parameters and for each of them there must be a string name and a STRING value. You are passing an array value instead, so the PHP processor is forced to convert it to a string using some lame built-in algorithm, which incurs issuance of the before-mentioned notice ("Array to string conversion in...").

So, in order to properly pass that array ($anarray) to the other side, you have to take care of its encoding (into a string) yourself, as well as the other side has to take care of its decoding (from a string).

My approach in such situations is JSON. It is suitable enough in almost all cases. All you have to do is apply the following technique:

$data=array(
    'anarray'=>json_encode($anarray),
    'var1'=>$var1,
    'var2'=>$var2
    );

And then, on the other side of the connection you would retrieve the original array the following way:

$anarray=json_decode($_POST['anarray'],true); // true indicates for associative array rather than an object


回答5:

If $anarray is an array, as I suspect it is, it shouldn't be. Turn it into a string, by concatenating or whatever appropriate method.

Edit: See Eric Butera's answer.



标签: php curl libcurl