在 curl 中将 post 作为数组或字符串发送时的区别

Difference when sending post as an array or as a string in curl

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

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

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

注释 here 说:

Note: Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

这可能是其他站点无法识别相同方式的原因。 作为解决方法,您可以使用 $post = http_build_query($post);

将数组转换为字符串