开发者

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

I am working with PHP cUrl to query a form. It does a POST query, so I am using an associative array. This is what the form looks like:

<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>

While doing my cUrl query, I have the following code:

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

Obviously in this case, PHP overwrites the previous 4 "var" assignments and only value5 gets passed as a parameter and I get an error saying I am missing value1..value4. I tried making "var" an array but that also prompts me an error.

Am I overlooking something? Thanks


The first problem is with the form. You have type="POST" when it should be method="POST". Your hidden fields should also be an array by using [] in the name attribute. Try the following instead:

<?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>

If you run that, you will see that the values are now in an array. To replicate this in your CURL request, you would do:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜