'Do PHP cURL options CURLOPT_HEADER and CURLOPT_RETURNTRANSFER conflict

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.

If I comment out the CURLOPT_RETURNTRANSFER option, then I get what I need, but it gets echoed out and the response is 1.

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

I've tried switching between http and https.

I am using PHP-5.5.27.



Solution 1:[1]

You're decoding without being sure that what you're getting is JSON. It most likely is not JSON, at least not all of the response. When you use CURLOPT_HTTPHEADER the response consists of text which starts with the response headers and then may have some JSON after them.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1