PHP cURL表单数据:多个变量,相同的名称,不同的值


PHP cURL Form data: Multiple variables, same name, diff. values

我正在使用PHP cUrl查询表单。它执行POST查询,所以我使用关联数组。这个表单看起来是这样的:

<form action="form.php" method="POST">
...
    <input type="hidden" name="var" value="value1">
    <input type="hidden" name="var" value="value2">
    <input type="hidden" name="var" value="value3">
    <input type="hidden" name="var" value="value4">
    <input type="hidden" name="var" value="value5">
...
</form>

在执行cUrl查询时,我有以下代码:

$postfields = array();
$postfields ["var"] = "value1";
$postfields ["var"] = "value2";
$postfields ["var"] = "value3";
$postfields ["var"] = "value4";
$postfields ["var"] = "value5";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_REFERER, $referer);
$result = curl_exec ($ch);
curl_close ($ch); 

显然在这种情况下,PHP覆盖了前面的4个"var"赋值,只有value5作为参数传递,我得到一个错误,说我缺少value1..value4。我试图使"var"一个数组,但这也提示我一个错误。

我是不是忽略了什么?由于

第一个问题是表单。当它应该是method="POST"时,你有type="POST"。通过在name属性中使用[],您的隐藏字段也应该是一个数组。试试下面的命令:

<?php

if (isset($_POST['submit']))
{
var_dump($_POST);
}
?>
<form action="" method="POST">
...
    <input type="hidden" name="var[]" value="value1">
    <input type="hidden" name="var[]" value="value2">
    <input type="hidden" name="var[]" value="value3">
    <input type="hidden" name="var[]" value="value4">
    <input type="hidden" name="var[]" value="value5">
    <input type="submit" name="submit" value="submit">
...
</form>

如果运行它,您将看到值现在在一个数组中。要在您的CURL请求中复制此内容,您可以这样做:

$postfields = array();
...
$postfields["var"][] = "value1";
$postfields["var"][] = "value2";
$postfields["var"][] = "value3";
$postfields["var"][] = "value4";
$postfields["var"][] = "value5";