Display JSON data from POST request in PHP - php

I have an apache2 server and php file to receive json via POST in my php code like this
$json = json_decode(file_get_contents('php://input'), true);
$mac_ = $json["code"];
$userId_ = $json["msg"];
and saving it to mysql. This work when I send post via python's requests but not when I'm recieving data from API android device. - When I look at the apache log file, there is a connection, so I'm assuming that some data are received, but because I can't touch that API android device I'm not sure if this part $json["code"] has a right parameter. I would like to know a way to save somewhere all recieved data from this part
$json = json_decode(file_get_contents('php://input'), true);
because I can't check it by echo or so

Related

Wordpress receiving a payload via a response url from third party API

I am sending & receiving JSON responses from a third party API, in one instance though they need to send a response to a url on my site ie: https://my-wordpress-site/api/confirm?transaction=T0efewgfweg78105 Can someone point me in the right direction on how to receive the payload from this response? The payload will be a JSON response like: “Status”: "Success" What script will I run on https://my-wordpress-site/api/confirm.php
If I understand the situation correctly
You can fetch this data with this snippet:
if(isset($_REQUEST['transaction']) && !empty($_REQUEST['transaction']))
{
$response_body = file_get_contents('php://input');
$data = json_decode($response_body);
}
php://input is a read-only stream that allows you to read raw data from the request body

How do I get data from Webhook to store in a database?

I am working with a Webhook based of of SendGrid's API v3. The Webhook is completely set up with an endpoint that SendGrid posts to, but I need to be able to receive that parsed data and store it in a database using PHP, but do not know how to do that.
I have worked with APIs before where I initiate the retrieval or POST of data, but when the API server is the one POSTing, how do I catch the data being parsed through the Webhook endpoint? I have some simple thus far, but am really unclear of how to tackle this:
<?php
$json = file_get_contents('https://example.com/webhook.php');
$json_decoded = json_decode($json, true);
$var_dump(json_decoded);
?>
I have tried sending multiple emails to the host, but every time I make this call I return NULL.
Try using the code from this example. This will give you the raw HTTP request body bytes to decode.
<?php
$data = file_get_contents("php://input");
$events = json_decode($data, true);
foreach ($events as $event) {
// Here, you now have each event and can process them how you like
process_event($event);
}
?>
More info on php://input

Get and Send file with PHP and RESTful API

One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/

manipulate POST data after sending it to PHP from PYTHON

I have an internal server that is generating JSON every few minutes. I need to pass this to and external server so I can manipulate the data and then present it in web interface.
Here is my python that send the data to PHP script:
x = json.dumps(data)
print '\nHTTP Response'
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")
conn.request("POST", "/recieve/recieve.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()
and Here is my PHP to receive the data
$data = file_get_contents('php://input');
$objJson = json_decode($data);
print_r ($objJson);
My python script return with response status 200 which is good and it returns my JSON. But on the PHP side I want to be able to store this information to manipulate and then have a web client grab at it. However it appears that even if I say
print_r ($objJson);
when I visit the .php page it does not print out my object. I suppose the data is gone because file::input will read only and then end?
Don't use file_get_contents()
Just:
if($_POST){ echo "WE got the data"; }
and print_r will help you with where to go from there, if you are unfamiliar with PHP arrays.
Try to use named parameter containing your JSON data while sending data to PHP and try to use the $_POST superglobal array in PHP (because you obviously connecting via cgi or similar interface not via cli).
You can see all the POST data by printing your $_POST array:
print_r($_POST);
Here is what I did in the end as a quick fix
the python
x = json.dumps(data)
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")
conn.request("POST", "/script.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()
then I realized that the PHP was receiving the post data but I was having a hard time manipulating it. So I just sent the JSON to a receiving PHP file that wrote the data as file and then has another JavaScript request grab that.
the php
if($_POST){ echo "WE got the data\n"; } //thanks rm-vanda
$data = file_get_contents('php://input');
$file = 'new.json';
$handle = fopen($file, 'a');
fwrite($handle, $data);
fclose($handle);
exit;
Then from my client just a ajax request for the file and parsed it on the client side.
Eventually I have to rethink this but it works for now. I also have to rewrite over the new.json file each time new data comes in or parse the old data out on the JavaScript success callback. Depends what you want to do.

How can I sending json data using Spring RestTemplate to PHP server

I am developing an android application and i using spring RestTemplate to get data from and post data to a PHP server. I tried to post data to PHP server, but PHP server got nothing. How can I post json data using Spring RestTemplate to PHP server and get the json from PHP server?
I solved the problem by myself. I add FormHttpMessageConverter to RestTemplate like this:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
And then I can post json data to PHP server. I got the json data in PHP server using:
$jsonData = $_POST['json'];
I fixed with
MultiValueMap<String, ArrayList<persona>> parts = new LinkedMultiValueMap<>();
parts.add("json", aaper);
restTemplate.postForLocation(url,parts);

Categories