首页 > 解决方案 > 在 curl 中以数组或字符串形式发送帖子时的区别

问题描述

我对 php 的 libcurl 有疑问。我正在使用这样的字符串发送帖子数据:

    $post="var1=val1&var2=val2";
    curl_setopt($this->ch, CURLOPT_URL, $url);
    curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->ch, CURLOPT_POST, 1);
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Accept-Encoding: gzip'));
    curl_setopt($this->ch,CURLOPT_ENCODING , "gzip");
    curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);

它工作得很好,但我想改用这样的数组:

    $post=array();
    $post['var1']="val1";
    $post['var2']="val2";

    curl_setopt($this->ch, CURLOPT_URL, $url);
    curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->ch, CURLOPT_POST, 1);
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Accept-Encoding: gzip'));
    curl_setopt($this->ch,CURLOPT_ENCODING , "gzip");
    curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);

但服务器似乎没有收到同样的东西,我有什么遗漏吗?

标签: phppostlibcurl

解决方案


这里的注释说:

注意:将数组传递给 CURLOPT_POSTFIELDS 会将数据编码为 multipart/form-data,而传递 URL 编码的字符串会将数据编码为 application/x-www-form-urlencoded。

这可能是其他站点不以相同方式识别的原因。作为一种解决方法,您可以使用将数组转换为字符串$post = http_build_query($post);


推荐阅读