Receive data in Json in PHP - php

I am posting data to my script file to receive data. In my script file, File.php, I am not able to get the object patient in the dumped results. When i do var_dump($get_patient_info->patient);,
it throws an error saying Object {patient} not found.
Could i be mapping the data wrongly?
PS: Beginner in Laravel
SendingData Controller
$hospitalData = [];
$hospitalData[] = [
'patient' => 'Mohammed Shammar',
'number' => '34',
],
$url = "https://example.com/file.php";
$client = new Client();
$request = $client->post($url, [
'multipart' => [
[
'name' => 'patient_info',
'contents' => json_encode($hospitalData),
],
],
]);
$response = $request->getBody();
return $response;
File.php
$get_patient_info = $_POST['patient_info'];
var_dump($get_patient_info);
Results
string(189) "[{"patient":"Mohammed Shammar","number":"34"}]"

You can json_decode and fetch the data as follows,
$temp = json_decode($get_patient_info);
echo $get_patient_info[0]->patient;
json_decode — Decodes a JSON string
Hope this helps.

Related

Guzzle with Laravel 9

I'm working on Lavravel 9 with guzzle to send some data in
the below code need to get some data from the database how can get data from the database?.
$response = Http::post('APIurl', [
"headers" => [
//header information
],
"body" => [
'title' => "**Get data from database**",
'body' => "**Get data from database**,
'userId' => 22
],
]);
Thank you
Assuming your API returns a json result, simply call the json() method on the Response object. If you want the raw response body, use body() instead.
For example, take github's api:
$response = Http::get('api.github.com'); // replace with your call
$body = $response->body(); // returns string
$json = $response->json(); // tries to return a json array.
To add data to your request, try passing a json string in the body.
$data = json_encode([
'title' => ...,
'body' => ...,
'user_id' => ...,
]);
$response = Http::post('your-api-here', [
'headers' => [
...
],
'body' => $data,
]);

Retrieve POST data sent with Guzzle (6.3) from Laravel

I am posting some data from my laravel app to another plain PHP page I have on my local server. The status code returned by Guzzle says it was successful but I am unable to access it. How can I do this?
I've tried using the Post method to retrieve value but no luck
Guzzle Function:
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
echo $response->getStatusCode();
Page Receiving POST DATA:
<?php
if (!empty($_POST['amnt'])) {
echo $_POST['amnt'];
}else
echo 'not found';
?>
I expect to be able to access the amount posted via post method but nothing is yielded.
Try somthing like that .
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
$contents = $response->getBody()->getContents();
$contents = json_decode($contents,true);
return ($contents);
On page Receiving POST DATA:
Response should be like this
return response()->json([
'status' => 'SUCCESS',
'code' => '200',
], 200);

Sending variables to another application and get the response from that?

I need to send data to another webpage of different application and it will send some json data which i need to use in further instruction.
I need to send some basic information like cus_name, cus_email, cus_phone to that webpage and that will send some data as json format.
i got the basic idea of how can i catch the json response : like that,
$client = new Client();
$body = $client->get('https://securepay.google.com/gwprocess/v3/api.php')->getBody();
$data = json_decode($body);
return redirect($data->GatewayPageURL);
How do i send those variables to and catch the response in same controller?
Thanks in advance.
You can send Query String Parameters in two ways.
Include them in the URI itself.
$response = $client->request('GET', 'https://securepay.google.com/gwprocess/v3/api.php?cus_name=name&cus_email=email&cus_phone=phone');
Or
Specify them using the query request option as an array
$response = $client->request('GET', 'https://securepay.google.com/gwprocess/v3/api.php', [
'query' => [
'cus_name' => 'name',
'cus_email' => 'email',
'cus_phone' => 'phone'
]
]);
Or for Post Requests:
$response = $client->request('POST', 'https://securepay.google.com/gwprocess/v3/api.php', [
'form_params' => [
'cus_name' => 'name',
'cus_email' => 'email',
'cus_phone' => 'phone'
]
]);
and then to get the response:
$result = json_decode($response->getBody());

Shapeshift API always returns "No Withdrawal Address Specified" error

I am using Shape Shift API for sending transaction with Guzzle. I am always getting the error given in title. My code given below:
$client = new GuzzleHttp\Client();
$data = [
"amount" => 1,
"withdrawal" => '0x23f016d7a8e408e5551ae7aa51b3fe1534165463',
"pair" => 'btc_eth',
"returnAddress" => '12stJs8vZNuuVfjZSSzpLPA96quNissk1b'
];
$result = $client->post( 'https://shapeshift.io/shift', [ 'Content-Type' => 'application/json' ],
[ 'json' => $data ] );
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
Same parameters work fine when using in Python.
You are doing the request wrong. The correct variant is with two parameters:
$result = $client->post('https://shapeshift.io/shift', ['json' => $data]);
Content type is configured automatically when you use json option.

Returning GuzzleHttp response object causes ERR_INVALID_CHUNKED_ENCODING in browser

I'm using guzzle 6 in laravel 5 to send a post request but I'm getting ERR_INVALID_CHUNKED_ENCODING when I try to access the request() in the method that handles the post request.
Here's my code:
Routes.php
Route::get('/guzzle', [
'as' => 'guzzle-test',
'uses' => 'TestController#getTest'
]);
Route::post('/guzzle', [
'as' => 'guzzle-post-test',
'uses' => 'TestController#postTest'
]);
TestController.php
public function getTest()
{
$client = new Client();
$data = [
'hey' => 'ho'
];
$request = $client->post(route('guzzle-post-test'), [
'content-type' => 'application/json'
], json_encode($data));
return $request;
}
public function postTest()
{
dd(getTest());
}
I getting to the post request handler since I've tried to diedump a string and it gets there, but if i call the request() I get that error. For what I've researched It may have something to with the content length, but after reading guzzle's docs and some stuff around the web I could find how to get and pass the content length appropriately in the request. Any help would be very appreciated!
First off, here's some test code which you should be able to adapt for your purposes (also see form_params in the docs for GuzzleHttp):
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return $response;
}
I just ran into the same issue and found that trying to return the response object in Laravel gave me ERR_INVALID_CHUNKED_ENCODING. Whereas, doing a dd() on the response itself showed me what I was actually wanting to see:
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
dd($response);
}
Unfortunately, without doing further research, I'm unable to explain why ERR_INVALID_CHUNKED_ENCODING keeps coming up when I try to return the client library's objects to the browser, but my initial inclination is that it's a data type issue.
As far as your question goes, you're not actually trying to get back the "request" but rather the response. According to http://docs.guzzlephp.org/en/latest/quickstart.html#using-responses, if you want to get the API response contained in the response object (or at least in my case, I did), you'll want to use the getBody() method:
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return $response->getBody();
}
And then of course, if you expect it to be a JSON response (i.e. REST), then simply pass it to json_decode() to get your associative array back.
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return json_decode($response->getBody(), true); // true = assoc. array
}
Hope that helps!

Categories