Guzzle6 streams doesn't give me the exact output - php

I have been trying to integrate guzzle into my app and I am having trouble with it. So, I get my response object from
$response = $client->post(.....);
The response of the endpoint is in JSON format. However, when I try to use it I get the following:
HTTP/1.1 200 OK Cache-Control: no-store Pragma: no-cache
{
// JSON HERE
}
Because of that I can't just use:
$array = json_decode($response->getBody()->getContents());
How, can I get rid of it showing my the response header in the output of body?

Related

Getting a value from json response without header from cURL

I want a the value of the "token" from the json array from the response i get after performing a cUrl post request. after print_r($response); it prints out all that. but i just want the json string and one particular value with php.
Here is my response. I don't want all this before the response
HTTP/1.1 200 OK<br/>
Content-Type: application/json<br/>
Content-Length: 312<br/>
Connection: keep-alive<br/>
Vary: Accept-Encoding<br/>
Status: 200 OK<br/>
Cache-Control: max-age=0, private, must-revalidate<br/>
Date: Wed, 22 Mar 2017 12:52:25 GMT<br/>
Strict-Transport-Security: max-age=31536000<br/>
X-Request-Id: 9418df03bea4e4884522b703d0eec504<br/>
X-UA-Compatible: IE=Edge,chrome=1<br/>
ETag: "dd4de4d3a6e4e499d6a034ce784d2d76"<br/>
X-Runtime: 0.633173<br/>
X-Content-Type-Options: nosniff<br/>
X-Rack-Cache: invalidate, pass<br/>
X-Powered-By: Phusion Passenger 5.0.28<br/>
Server: nginx/1.10.0 + Phusion Passenger 5.0.28
{"response_code":"00","response_text":"Mobile wallet payment request has been issued.","description":"You will receive a bill prompt shortly on your number 0546653444 with invoice no. 201562656, kindly complete it.","transaction_id":"DTV408402","token":"8268dfffa46a16b0665a76","mobile_invoice_no":"201562656"}
You need to tell cURL that you don't want the header:
curl_setopt($ch, CURLOPT_HEADER, 0);
you can use php's explode() function on this response. Or you can adjust your curl request to not return headers with your requests.
$split=explode("\n\n",$response);
$array=json_decode($split[1],true);
var_dump($array);
if this does not work, modify explode function to split on "\r\n\r\n" instead of "\n\n";
you can do it with JSON decode.
$json = $Your_respone_variable;
$obj = json_decode($json);
print $obj->{'token'}; // token can be replaced by any other key of your JSON
For more informations take a look at:
http://php.net/manual/de/function.json-decode.php

How to prevent CRLF injection (Http response splitting) in php

I did R&D on prevention of CRLF injection in php, but i didn't find any solution in mycase, as I'm using a burp suite tool to inject some headers using CRLF characters like the below.
// Using my tool i put CRLF characters at the start of my request url
GET /%0d%0a%20HackedHeader:By_Hacker controller/action
//This generates an header for me like below
HackedHeader:By_Hacker
So i can modify all headers by doing just like above
This tool is just like a proxy server so it catches the request and gives the response and we can modify the response in the way we want.
So i'm just modifying the response by injecting some headers using CRLF characters. Now the Server responds to this request by injecting the CRLF characters in the response.
I'm just worried as header fields like Pragma, Cache-Control, Last-Modified can lead to cache poisoning attacks.
header and setcookie contain mitigations against response/header splitting, But these can't support me in fixing the above issue
Edit
When i request to mysite.com contact us page like below This is the request I captured in my tool like below
Request headers:
GET /contactus HTTP/1.1
Host: mysite.com
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
And i get the Response HTML for the above request
Now for the same request using the tool i'm adding custom headers just like below
Request Headers:
GET /%0d%0a%20Hacked_header:By_Hacker/contactus HTTP/1.1
Host: mysite.com
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Response Headers:
HTTP/1.1 302 Found
Date: Fri, 10 Jul 2015 11:51:22 GMT
Server: Apache/2.2.22 (Ubuntu)
Last-Modified: Fri, 10 Jul 2015 11:51:22 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Location: mysite.com
Hacked_header:By_Hacker/..
Vary: Accept-Encoding
Content-Length: 2
Keep-Alive: timeout=5, max=120
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
You can see the injected header Hacked_header:By_Hacker/.. in the above response
Is there anyway in php or apache server configuration to prevent such kind of headers' hack?
Not sure why all the down votes - infact, it is an interesting question :)
I can see that you have tagged CakePHP - which means your app is using Cake Framework... Excellent! If you are using Cake 3 , it is automatically strip off : %0d%0a
Alternatively, where you receive the response header, just strip off %0d%0a and you are good!
Where things like these could be applied - a 3rd party API response or say.... a Webhook response! or a badly sanitized way to handle intl.. example : lang=en to lang=fr where the GET param is directly set as response header... That would not be a wise move!
Ideally, the responses will be as GET and not in the header but either way just strip the %0d%0a and you are good.
Answering your edit.
You can see the injected header Hacked_header:By_Hacker/.. in the above response
That injected header cannot be controlled or stopped, mate. We do not have control over what the other server does.
The question is.. What do you do with the response header?
The answer is... You sanitize it, as ndm said you need to sanitize the input.. What you get as a response IS an input. As soon as you detect %0d%0a, discard the response.
Need code work?
<?php
$cr = '/\%0d/';
$lf = '/\%0a/';
$response = // whatever your response is generated in;
$cr_check = preg_match($cr , $response);
$lf_check = preg_match($lf , $response);
if (($cr_check > 0) || ($lf_check > 0)){
throw new \Exception('CRLF detected');
}

Php Api html reponse display data issue using php

I am using an api to get scorecard of matches using php, response is coming from api as text/html so I conveted this response to json using json_encode first and then converted to json_decode for display but I am not getting matchId wise results.
API RESPONSE HEADERS
Connection: keep-alive
Content-Type: text/html
Date: Tue, 09 Dec 2014 13:36:11 GMT
Server: Mashape/5.0.5
Transfer-Encoding: chunked
X-Powered-By: PHP/5.2.17
demo: click here
var_dump($response);
Code Here
$html = json_encode($response);
$json = json_decode($html);
foreach($json as $data => $value)
{
echo $value->matchId;
}
above var_dump giving response, foreach loop printing nothing.
demo link scroll page at bottom you should see '------------' this message. foreach loop print start here
You need to specify if you want to get an associative array and not an object from json_decode . Therefore, you should use
json_decode($response, true)
For more information see here

How to return just JSON response from Laravel 4 REST API?

I have a Laravel RESTful API setup that needs to return data in JSON format to an app on one of my subdomains ( and thus not within the Laravel app itself ).
In the REST I am returning like:
return \Response::json(array(
"status" => "success",
"type" => "client",
"message" => "Nothing to see here!"
));
In my Class on the subdomain app I am simply trying to return this response to a view print the output for testing.
I would hope that I just get back JSON, but when I do a simple:
echo $resp;
I get nothing
If I do a:
print_r( $resp );
or
json_decode( $resp );
I get:
HTTP/1.1 200 OK
Server: nginx/1.6.2
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.4.35
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Date: Sat, 06 Dec 2014 04:18:15 GMT
Set-Cookie: laravel_session=eyJpdiI6Ik5DdDFGK2tJQ3ZCVkJPQnRtZHRaU2c9PSIsInZhbHVlIjoiT2tXSTJWYzRKUXZncG9NOFZBYkhOUTZRaUg1c3NmUXlHTjF5bzYyaTZRYUY4S3VBMEdwdjdwdXNUNHkwblppV1I5YUFsY2dodGNyRHh5SmZYeGFjcWc9PSIsIm1hYyI6Ijc0Mzg3MGNlNTBiYTEyNTE3MzNhZDVjNjUzNzMwNzk0ZTMwN2MwYmFiNDIyMGE0N2MyNTQxMDNlMDdiOGFmOTQifQ%3D%3D; expires=Sat, 06-Dec-2014 06:18:15 GMT; path=/; httponly
{"status":"success","type":"client","message":"Nothing to see here!"}
I don't want all of that headers stuff in my response like that. Or I am receiving and trying to parse it incorrectly. What am I doing wrong here?
Ok, this was a dumb mistake not with the REST API, but with the cURL call to the API.
If this ever happens to you just check and make sure you do not have:
curl_setopt($ch, CURLOPT_HEADER, 1);
That will output the headers with the response and mess up your day. I hope this helps others.
My return is like this:
return Response::json(array($data));
Just store array to a variable and call that variable on to the response.

How to tell ZF2's JsonModel to return text/plain instead of application/json?

Using PHP Zend Framework 2.0.2, I return JSON data after an AJAX call. Obviously, Internet Explorer 9 wants to download the data instead of returning it to the calling Javascript method.
Posts like this one and this one say to use Content-Type: text/plain instead of Content-Type: application/json, but how do I do this with ZF2's JsonModel? I'm new to it...
I imagine I have to set something in the setOptions() array, but what?
public function testJsonAction()
{
$jsonResponse = new JsonModel(array('success' => false));
$jsonResponse->setOptions(array(
// ** Should I put something here? What? **
));
return $jsonResponse;
}
I tried using these:
$this->getResponse()->getHeaders()->addHeaderLine('Content-Type', 'text/plain');
$this->getResponse()->getHeaders()->addHeaderLine('Content-Disposition', 'inline; filename="textdata.json"');
but it doesn't change the HTTP Content-Type in the response headers:
Key Value
Response HTTP/1.1 200 OK
Content-Type application/json
Server Microsoft-IIS/7.5
X-Powered-By PHP/5.3.13
Set-Cookie ZDEDebuggerPresent=php,phtml,php3; path=/
Content-Disposition inline; filename="textdata.json"
X-Powered-By ASP.NET
Date Wed, 10 Oct 2012 13:19:42 GMT
Content-Length 17
Thanks for your help!
Because when \Zend\Mvc\MvcEvent::EVENT_RENDER event happen, the JsonStrategy will change content-type again. Source code is in
Zend\View\Strategy\JsonStrategy->injectResponse();
So in order to replace content-type into yours, you need to use EventManager to inject your custom header after JsonStrategy injected.
try below codes in your controller:
$this->getServiceLocator()->get('Application')->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function($event){
$event->getResponse()->getHeaders()->addHeaderLine('Content-Type', 'text/plain');
}, -10000);

Categories