I’ve been trying to create a connection between two hosts with a POST request sent as JSON using cURL in PHP. My primary objective is to send data from Host A to Host B (labelled for clarity).
First, looking at network tools in the sender browser, the request type is always GET instead of POST, despite using CURLOPT_POSTFIELDS and CURLOPT_POST. Secondly, the data is not printing/echoing in the receiving browser. However, the hardcoded outputs in the receiving script are printing in both browsers. I’ve tried using CURLOPT_CUSTOMREQUEST ‘POST’ to no avail.
Sender JSON tab: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 59 of the JSON data
Sender Raw Data tab: {"ChangeType":"renamed","Path":"C:File1","Param3":"Yes"}receive_jsonpost_test.php is running renamedC:File1YesObject id #1
Code:
<?php
// HOST A (sender)
header("Content-Type:application/json");
$testobj = array(
'ChangeType' => 'renamed',
'Path' => 'C:\File1',
'Param3' => 'Yes'
);
$url = '[redacted].edu/receive_jsonpost_test.php';
$ch = curl_init($url);
$payload = json_encode($testobj);
print($payload);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$result = curl_exec($ch);
curl_close($ch);
print($result);
?>
<?php
// HOST B (recipient)
print('receive_jsonpost_test.php is running ');
$json = file_get_contents('php://input');
$data = json_decode($json);
print($data->ChangeType);
print($data->Path);
print($data->Param3);
print($data);
I know this is probably a pretty basic problem, but I’m fairly new to applied host-to-host communication and any help would be greatly appreciated. Thanks.
2
Answers
If you’re trying to interpret the response from Host A, ie…
as JSON, you won’t have much luck since Host B does not respond with JSON. Host B’s code should look more like this…
You should also remove this line from Host A as it too will invalidate a JSON response…
Your browser isn’t making the request to Host B, PHP is. If your browser makes a GET request to Host A, then that’s all it will see.
If all you want to do is send data to HOST B and have B echo the received data back to HOST A:
Remove this from HOST A:
It will send headers to the Browser. The headers should come from HOST B response headers.
Same goes for
Again, headers should come come from HOST B response headers.
HOST A request:
HOST B possible responses
OR If you want to support both POST and GET
If you really need JSON:
HOST B
OR
OR
If you want to do a GET request in a Browser: