简体   繁体   English

PHP cURL选项CURLOPT_HEADER和CURLOPT_RETURNTRANSFER是否冲突

[英]Do PHP cURL options CURLOPT_HEADER and CURLOPT_RETURNTRANSFER conflict

I am using cURL with php to authenticate to an API. 我正在使用cURL和php对API进行身份验证。 Like this: 像这样:

$ch = curl_init();
$headers    = [];
$headers[]  = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $this->body ));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->response = json_decode( curl_exec($ch) );
curl_close ($ch);

The body of the request response contains status code and if request has been successfull the user object. 请求响应的主体包含状态代码,如果请求已成功,则包含用户对象。 This is an anonymous request and it returns the token in the response headers. 这是一个匿名请求,它在响应头中返回令牌。

My problem: The script's above response is null. 我的问题:脚本的上面响应是null。

If I comment out the CURLOPT_RETURNTRANSFER option, then I get what I need, but it gets echoed out and the response is 1. 如果我注释掉CURLOPT_RETURNTRANSFER选项,那么我得到我需要的东西,但它会被回显,响应为1。

If I comment out the CURLOPT_HEADER option, then I get only the body of the response. 如果我注释掉CURLOPT_HEADER选项,那么我只得到响应的主体。

I've tried switching between http and https. 我试过在http和https之间切换。

I am using PHP-5.5.27. 我使用的是PHP-5.5.27。

You're blindly decoding without being sure that what you're getting is JSON. 你是盲目解码而不确定你得到的是JSON。 Short answer: it's not. 简短的回答:事实并非如此。 It's text which contains the headers and maybe some JSON after them. 它的文本包含标题,可能还有一些JSON。

Do something like: 做类似的事情:

$ch = curl_init();
$headers    = [];
$headers[]  = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $this->body ));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$actualResponseHeaders = (isset($info["header_size"]))?substr($response,0,$info["header_size"]):"";
$actualResponse = (isset($info["header_size"]))?substr($response,$info["header_size"]):"";

$this->response = json_decode( $actualResponse );
curl_close ($ch);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM