在php中使用curl进行表单发布

时间:2011-05-13 15:09:53

标签: php curl

您好我想发布卷曲,但我无法做到这一点

这是我在Csharp中尝试过的,它可以工作,但是php版本无效

C#

  WebRequest request = WebRequest.Create("http://www.somesite.com/somepage.php");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string postString = "email=email@email.com&dueday=1&duemonth=2&dueyear=3&Submit=Submit";
            ASCIIEncoding ascii = new ASCIIEncoding(); 
            byte[] postBytes = ascii.GetBytes(postString.ToString());
            request.ContentLength = postBytes.Length;

            Stream postStream = request.GetRequestStream(); 
            postStream.Write(postBytes, 0, postBytes.Length); 
            postStream.Close(); 
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

<?php

if (isset($_POST['email']) && trim($_POST['email']) != "") {
    //filter out everything but the needed information
    $cleanquery = array();
    foreach ($_POST as $key=>$value) {
        //newsletter name
        if (stripos($value, 'something') !== false) {
            $cleanquery[$key] = $value;
        }
        if ($key == 'dueday' || $key == 'duemonth' || $key == 'dueyear' || $key == 'email') {
            $cleanquery[$key] = $value;
        }
    }
    $queryline = "";
    $i=0;
    foreach ($cleanquery as $key=>$value) {
        if ($i == 0) {
            $queryline .= $key . "=" . $value;
        } else {
            $queryline .= '&amp;' . $key . '=' . $value;
        }
        $i++;
    }
    $url = 'http://www.somesite.com/somepage.php';
    $ch = curl_init();
       curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST,4);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $queryline);
    curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    echo $info['http_code'];
}
?>

2 个答案:

答案 0 :(得分:2)

$queryline = "";
$i=0;
foreach ($cleanquery as $key=>$value) {
    if ($i == 0) {
        $queryline .= $key . "=" . $value;
    } else {
        $queryline .= '&amp;' . $key . '=' . $value;
    }
    $i++;
}

您无需执行此操作,因为CURLOPT_POSTFIELDS可以设置"as an array with the field name as key and field data as value"

curl_setopt($ch, CURLOPT_POST,4);

不知道为什么你最后有4个。

答案 1 :(得分:0)