简体   繁体   中英

form posting using curl in php

Hi i am trying to post curl but i am not able to do it

this is what i tried it in Csharp and it works but php version is not working

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

<?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'];
}
?>
$queryline = "";
$i=0;
foreach ($cleanquery as $key=>$value) {
    if ($i == 0) {
        $queryline .= $key . "=" . $value;
    } else {
        $queryline .= '&amp;' . $key . '=' . $value;
    }
    $i++;
}

You don't need to do this because CURLOPT_POSTFIELDS can or be setup "as an array with the field name as key and field data as value" .

curl_setopt($ch, CURLOPT_POST,4);

Not sure why you have the 4 at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM