PHP cURL选项CURLOPT_HEADER和CURLOPT_RETURNTRANSFER是否冲突 [英] Do PHP cURL options CURLOPT_HEADER and CURLOPT_RETURNTRANSFER conflict

查看:74
本文介绍了PHP cURL选项CURLOPT_HEADER和CURLOPT_RETURNTRANSFER是否冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将cURL与php一起使用以对API进行身份验证。
像这样:

I am using cURL with php to authenticate to an 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.

如果我注释掉CURLOPT_RETURNTRANSFER选项,那么我得到了所需的内容,但它得到了回应,响应为1。

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_HEADER选项,那么我只会得到响应的正文。

If I comment out the CURLOPT_HEADER option, then I get only the body of the response.

我试图在http和https之间切换。

I've tried switching between http and https.

我正在使用PHP-5.5.27。

I am using PHP-5.5.27.

推荐答案

您正在盲目解码,不确定您得到的是JSON。简短的回答:不是。它是包含标题的文本,后面可能还有一些JSON。

You're blindly decoding without being sure that what you're getting is JSON. Short answer: it's not. It's text which contains the headers and maybe some JSON after them.

做类似的事情:

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

这篇关于PHP cURL选项CURLOPT_HEADER和CURLOPT_RETURNTRANSFER是否冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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