Question

[Solved] 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:

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.

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);
Respondent: apokryfos

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy