使用数组 post 到具有相同输入名称的 cURL

use arrays to post to cURL with same input name

我想提交数组到 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>

我希望结果像这样发送到 curl:

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 文件:

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

结果:

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

如何将结果发送到 cURL?

根据发布的值构建查询字符串:

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

并通过 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);

有一个函数 http_build_query() 可以为您完成这项工作。

例如:

$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);

你的实际问题是

How do I POST an array of data using cURL?

此问题已得到解答here

您将使用函数 http_build_query() 从您的索引 comment 数组构建一个 URL 编码字符串。

这段代码应该可以解决问题。

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

您可能需要设置 Content-Type 将 header 设置为 multipart/form-data,如 curl_setopt documentation 中所述。