如果CURLOPT_POST设置与curl_setopt_array,PHP curl重置内容长度? [英] PHP curl resets content-length if CURLOPT_POST is set with curl_setopt_array?

查看:189
本文介绍了如果CURLOPT_POST设置与curl_setopt_array,PHP curl重置内容长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来 curl_setopt_array 与只是多次调用 curl_setopt 不同。考虑这个脚本:

It looks like curl_setopt_array is different from just multiple invocations of curl_setopt. Consider this script:

$ch = curl_init('http://www.stackoverflow.com/');

[options]

curl_exec($ch);

var_dump(curl_getinfo($ch));

现在,如果 [options] 是以下之一:

Now it sends a proper request if [options] are one of these:

curl_setopt_array($ch, array(
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => array('a' => 'b'),
));

curl_setopt_array($ch, array(
  CURLOPT_POSTFIELDS => array('a' => 'b'),
));

curl_setopt($ch, CURLOPT_POSTFIELDS, 'a=b');
curl_setopt($ch, CURLOPT_POST, 1);

但不是这样:

curl_setopt_array($ch, array(
  CURLOPT_POSTFIELDS => array('a' => 'b'),
  CURLOPT_POST => true,
));

似乎如果 CURLOPT_POST CURLOPT_POSTFIELDS 后设置。除非它工作正常如果设置与 curl_setopt 而不是 curl_setopt_array

It seems that the content-length is reset if CURLOPT_POST is set after CURLOPT_POSTFIELDS. Except it works ok if set with curl_setopt instead of curl_setopt_array.

这是为什么?

推荐答案

$ c> CURLOPT_POST ,则帖子将作为 application / x-www-form-urlencoded 发送。

When you specify CURLOPT_POST, the post is sent as application/x-www-form-urlencoded.

但是,从 curl_setopt 手册页:


数组到CURLOPT_POSTFIELDS会将数据编码为
multipart / form-data,而传递URL编码字符串将编码
数据作为application / x-www-form-urlencoded。

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.

所以当你做

curl_setopt_array($ch, array(
  CURLOPT_POSTFIELDS => array('a' => 'b'),  // multipart/form-data
  CURLOPT_POST => true,                     // application/x-www-form-urlencoded
));

数据设置为 mulpart / form-data (通过将 CURLOPT_POSTFIELDS 设置为数组)然后重置为 application / x-www-form-urlencoded (通过将 CURLOPT_POST 设置为true)。

The data is being set as mulpart/form-data (by setting CURLOPT_POSTFIELDS to an array) and then reset as application/x-www-form-urlencoded (by setting CURLOPT_POST to true).

其他示例工作,因为您不更改类型数据已设置。

The other examples work because you're not changing the type once the data is set.

这篇关于如果CURLOPT_POST设置与curl_setopt_array,PHP curl重置内容长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆