0

I want to submit arrays to cURL

<form action="post.php" method="post">
    <input name="comment[]" value="oh"/><br>
    <input name="comment[]" value="wow"/><br>
    <input name="comment[]" value="like"/><br>
    <input type="submit" />
</form>

and I want the result send to curl like this:

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, "0=oh&1=wow&2=like");
    $hasil = curl_exec ($ch);
    curl_close ($ch);

post.php file:

$inputs = $_POST['comment']; print_r($inputs);

and result:

Array
(
    [0] => oh
    [1] => wow
    [2] => like
)

How can I send the result to cURL?

Daniel Kmak
  • 16,209
  • 7
  • 65
  • 83
  • 1
    possible duplicate of [Post multidimensional array using CURL and get the result on server](http://stackoverflow.com/questions/14625101/post-multidimensional-array-using-curl-and-get-the-result-on-server) – nlu Jan 27 '15 at 14:55

3 Answers3

0

Build the query string from the posted values:

$query_string = http_build_query($_POST['comment']);

And submit it via curl:

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $query_string);
$hasil = curl_exec ($ch);
curl_close ($ch);
0

There's a function http_build_query() which will do this job for you.

e.g:

$querystring = http_build_query($inputs);

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $querystring);
$hasil = curl_exec ($ch);
curl_close ($ch);
Maltronic
  • 1,645
  • 8
  • 18
0

Your actual question is

How do I POST an array of data using cURL?

This question has been answered here.

You would use the function http_build_query() to build a URL encoded string from your indexed comment array.

This code should do the trick.

curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($inputs))

You may need to set the Content-Type header will be set to multipart/form-data, as described in the curl_setopt documentation.

Community
  • 1
  • 1
danhardman
  • 623
  • 1
  • 6
  • 16