php+ccurl无法设置post方法


php + curl cannot set post method

我试图用php和curl发出一个post请求。这是我的代码

//PHP 5.3.5 and curl: 7.18.2
$ch = curl_init();
if(!empty($save_cookie)){
    curl_setopt($ch, CURLOPT_COOKIEJAR, $save_cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $save_cookie);
}else{
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/post.php');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pars);
curl_setopt($ch, CURLOPT_HEADER, $header);
curl_setopt($ch, CURLOPT_NOBODY, !$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (curl_errno($ch)) {
    return false;
}
curl_close($ch);
return $postResult;

在http://localhost/post.php,我写

print_r($_SERVER);

卷曲的结果返回总是

[REQUEST_METHOD] => GET

删除CURLOPT_NOBODY选项,它就会工作。或者将其放置在CURLOPT_POST线上。

我想我曾经遇到过这种情况,当我试图只获取响应的头部时。设置

curl_setopt($ch, CURLOPT_NOBODY, true);

有效地指示curl发出不是POST请求的HEAD请求。我认为没有办法只从POST中获取标头(并在收到标头后丢弃连接)。作为副作用,将CURLOPT_NOBODY设置为false将请求类型设置为GET。。。

您真的需要CURLOPT_NOBODY标志吗?

尝试移动

curl_setopt($ch, CURLOPT_NOBODY, !$body);

前的行

curl_setopt($ch, CURLOPT_POSTFIELDS, $pars);

行。

curl/set_opt页面上有一篇有趣的帖子,揭示了这种行为:

如果您的POST数据似乎正在消失(POST数据为空,请求正在由服务器作为GET处理),请尝试重新排列CURLOPT_POSTFIELDS设置与CURLOPT_NOBODY。CURLOPT_POSTFIELDS具有在CURLOPT_NOBODY设置之后,因为如果它在它之后删除告诉您的URL目标请求是POST而不是GET。