如何删除libcurl POST请求响应中收到的额外数据?

时间:2015-03-22 13:37:52

标签: php c libcurl

我使用C程序使用libcurl库将数据发送到PHP文件。代码如下所示:

CURL *curl;
CURLcode res;
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
struct curl_slist *headers=NULL;

curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl)
{
    curl_formadd(&formpost,
        &lastptr,
        CURLFORM_COPYNAME, "name",
        CURLFORM_COPYCONTENTS, "Peter",
        CURLFORM_CONTENTTYPE, "text/plain",
        CURLFORM_END
    );

    curl_formadd(&formpost,
        &lastptr,
        CURLFORM_COPYNAME, "project",
        CURLFORM_COPYCONTENTS, "Project",
        CURLFORM_CONTENTTYPE, "text/plain",
        CURLFORM_END
    );

    curl_formadd(&formpost,
        &lastptr,
        CURLFORM_COPYNAME, "submit",
        CURLFORM_COPYCONTENTS, "Send",
        CURLFORM_END
    );

    curl_easy_setopt(curl, CURLOPT_URL, "http://maxp.biz/curl.php");
    //curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl/1.0 (Linux 2.6.32.9; )");

    headers = curl_slist_append(NULL, "Content-Type: application/x-www-form-urlencoded; charset=utf-8");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    res = curl_easy_perform(curl);

    /* Check for errors */
    if(res != CURLE_OK)
    {
        DbgSerialPrn("\rcurl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
        return -1;
    }

    DbgSerialPrn("\rResult: %s\r", chunk.data);

    curl_slist_free_all(headers);
    curl_formfree(formpost);
    curl_easy_cleanup(curl);
}
else
{
    DbgSerialPrn("\rCurl Init not successful");
    return -1;
}

if(chunk.data)
{
    free(chunk.data);
}

curl_global_cleanup();

DbgSerialPrn()方法是用于打印结果的自定义方法。当我收到PHP文件的数据时,输出如下:

array(4) { ["_GET"]=> array(0) { }  ["_POST"]=>  array(1) {   
["--------------------------3b700fd71429022e
Content-Disposition:_form-data;_name"]=> string(323) ""name"
Content-Type: text/plain

Peter
--------------------------3b700fd71429022e
Content-Disposition: form-data; name="project"
Content-Type: text/plain

Project
--------------------------3b700fd71429022e
Content-Disposition: form-data; name="submit"

Send
--------------------------3b700fd71429022e--
"  }  ["_COOKIE"]=>  array(0) {  }  ["_FILES"]=> array(0) { }}

首先,为什么PHP文件将数据作为一个大字符串而不是几个单独的变量接收,我该如何处理它?二,如何摆脱PHP文件在$ _POST数组中收到的额外数据?

1 个答案:

答案 0 :(得分:0)

由于您似乎无法上传文件内容,因此请尝试从CURLFORM_CONTENTTYPE丢失curl_addform部分。