I'm trying to read the contents of a webhook notification in php. The content of the request is in the link below:
Link POST
HEADERS:
Pragma: no-cache
X-Request-Id: fec7f2ea-ae08-4fc1-9f81-b7ed9b976100
X-Newrelic-Transaction: PxQDWVNWCgBWBlJWVldRV1dUFB8EBw8RVU4aVgANAQAAA1tSBQBVBFUFUkNKQQtVVlNTUVZQFTs=
Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
Connect-Time: 2
Connection: close
Content-Length: 931
Cache-Control: no-cache
User-Agent: Java/1.7.0_72
Accept-Encoding: gzip
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Via: 1.1 vegur
X-Newrelic-Id: UgcDUFdVGwQAXFdRBAU=
Host: requestb.in
Total-Route-Time: 0
FORM/POST PARAMETERS:
data: { "event": "PAYMENT_UPDATED", "payment": { "object": "payment", "id": "pay_158657847699", "customer": "cus_artujit2nfYe", "value": 160.0, "netValue": 155.75, "originalValue": null, "nossoNumero": "34271724", "description": "", "billingType": "BOLETO", "status": "PENDING", "dueDate": "21/12/2016", "paymentDate": null, "invoiceUrl": "", "boletoUrl": "", "invoiceNumber": "00507815", "externalReference": null, "deleted": false } }
I tried unsuccessfully through the line code: $datasrc = $_POST;
I also tried to read with $ _REQUEST unsuccessfully.
How to read the content in php?
No clue what webhook is or does. But if it is sent as as POST request to a page in PHP, the data posted will be present in the $_POST array.
To see what's in it: var_dump($_POST); will show you the array and it's structure.
To get the value of a specific key: $variable = $_POST['key']; will do the trick.
If I interpret the stuff you posted correctly the json encoded content should be in $_POST['data']; .
To decode the json encoded string, PHP has helpful functions such as json_decode.
$data=json_decode($_POST['data'], true); should give you a PHP array with the data.
Related
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 1 year ago.
I am using jQuery to submit the following request:
$.ajax({
url: encodeURI('/server/api/user/update.php/'),
method: 'POST',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + utility.getJsonWebToken()
},
data: JSON.stringify(e.model),
dataType: 'json'
})
And I have the following PHP code that verifies that the request is valid and contains the necessary body:
// check for bad method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
$returnedJson['error'] = 'The supplied request method is not supported for the requested resource. This resource expects a POST request.';
echo json_encode($returnedJson);
return;
}
// check for bad request
$errors = array();
$user = new UserModel();
foreach (UserModel::$RequiredColumnNames as $property) {
$success = ControllerUtility::isValueInRequest($_POST, $property);
if (!$success) {
array_push($errors, $property);
continue;
}
$user->$property = $_POST[$property];
}
if (count($errors) > 0) {
http_response_code(400);
$returnedJson['error'] = 'Malformed request syntax. The following properties are missing from the request: ' . join(', ', $errors);
echo json_encode($returnedJson);
return;
}
Every time I submit the request, I get 400 error with the 'Malformed request syntax. The following properties are missing from the request: ...' error message.
I echoed the $_POST and $_REQUEST but in both instances and empty array is returned.
I verified that the request headers is a POST:
POST /server/api/user/update.php/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Authorization: Bearer -removed-
X-Requested-With: XMLHttpRequest
Content-Length: 180
Origin: http://localhost
Connection: keep-alive
Referer: -removed-
Sec-GPC: 1
And the fields are included in my request JSON:
{
"CreatedBy": null,
"CreatedOn": "2021-02-28 13:53:54",
"DeletedOn": null,
"Email": "-removed-",
"ModifiedBy": "1",
"ModifiedOn": "2021-02-28 16:35:51",
"UserId": "1",
"Username": "Adminn"
}
I have even removed the content-type header from my PHP without success. I've also tried just passing e.model instead of calling stringify in the AJAX request. At this point I'm at a loss as to what I'm doing wrong.
// echo the json string from php://input.
file_get_contents('php://input');
I need to receive in PHP an http post from RestSharp / 105.2.3.0, supposedly send me the following:
POST / api / Msg HTTP / 1.1
Accept: application / json
Authorization: Basic K9ykc3QyOmlmZWlnb2hjaGFpZ2hpZWxpaH53
User-Agent: RestSharp / 105.2.3.0
Content-Type: application / json
Host: xxx.xxx.xxx.xxx
Content-Length: 80
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{"Name": "Bear", "LastName": "Lukas", "time": 797, "option": 1}
I tried to use the following code in php but it did not work, any ideas?
<?php
$json_params=file_get_contents("php://input");
$decoded_params = json_decode($json_params,true);
foreach ($decoded_params as $dp){
echo $dp;
}
I am using cURL and REST to access a database and a query search, i am getting the following response when i use echo $response:
HTTP/1.1 200 OK Date: Fri, 05 Aug 2016 06:53:02 GMT Server: Apache Content-Language: en-US RNT-Time: D=58292 t=1470379982660626 RNT-Machine: 128.65 Transfer-Encoding: chunked Content-Type: application/json { "items": [ { "tableName": "Country", "count": 1, "columnNames": [ "id" ], "rows": [ [ "12" ] ] } ], "links": [ { "rel": "self", "href": "https://test.cust.com/services/rest/connect/v1.3/queryResults?query=select%20ID%20from%20CO.Country%20where%20CO.Country.Country=%27USA%27" }, { "rel": "canonical", "href": "https://test.cust.com/services/rest/connect/v1.3/queryResults" }, { "rel": "describedby", "href": "https://test.cust.com/services/rest/connect/v1.3/metadata-catalog/queryResults", "mediaType": "application/schema+json" } ] }
i tried to use JSON_decode() but so far i got nowhere, how can i get my parameters here ? to be more specific, the "id" value.
If I get you right you have 2 options:
turn off receiving headers curl_setopt($ch, CURLOPT_HEADER, 0)
break your response by \r\n\r\n, you'll get header and body
list($header, $body) = explode("\r\n\r\n", $response, 2)
The response which posted here is seems like server response sending to the client browser,
so, you have few of options to parse this data
In case of this response must be parsed using PHP then you can try parsing data using parse_str() in PHP by following way.
if (FALSE !== (stripos($response, '{'))) {
$data = trim(substr($response, stripos($response, '{')));
$data_arr = array();
parse_str($data, $data_arr);
print_R($data_arr);
//Digging down using parse_str() in php
} else {
echo "No data found.";
}
Either use client side javascript/jquery/client side script to parse json from response on browser.
Returning header as array using Curl
You don't need to use JSON_decode().
Use:
$obj = $_POST['items']; // for post
for get:
$obj = $_GET['items'];
With the help of #evilive, i was able to get it to work:
1- turn of receiving headers curl_setopt($ch, CURLOPT_HEADER, 0)
2- $test=$res->items[0]->rows[0];
echo $test[0];
$response;//Suppose your respond is this.
$obj = json_decode($response);
Then you can access your parameters.
Example:
$obj-> items
I'm trying to create a PHP script which sends some JSON data together with a zipped file to an API (InMobi) but I can't get it to work. I usually just set the header to application/json and use curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); where $data is a PHP array but how do I attach the file on top of that?
The request should look like this:
Content-Type: multipart/form-data; boundary=AYip2bnLbOw0R2vf8lDZ71pon3CDottfPlckt-E Content-Disposition: form-data; name="payload"
Content-Type: application/json; charset=US-ASCII
Content-Transfer-Encoding: 8bit
{
"campaign": {
"name": "campaign-with-banner-ad",
"dailyBudget": "2000.00",
"startDate": "2012-03-10",
"endDate": "2012-05-31",
"action": "create",
"adGroups": [
{
"countryId": 94,
"name": "First AdGroup",
"bid": "1.89",
"landingURL": "http://test.inmobi.com/sampleapp",
"ctaDetails": {
"id": "1"
},
"action": "create",
"ads": [
{
"type": "banner",
"name": "From Root",
"filePath": "/",
"altText": "3 img add",
"action": "create"
},
{
"type": "banner",
"name": "From ad1",
"filePath": "/ad1/",
"action": "create"
},
{
"type": "banner",
"name": "From ad2",
"filePath": "/ad2/",
"action": "create"
}
]
}
]
}
}
--AYip2bnLbOw0R2vf8lDZ71pon3CDottfPlckt-E
Content-Disposition: form-data; name="zipFile"; filename="banners.zip" Content-Type: application/octet-stream; charset=ISO-8859-1
Content-Transfer-Encoding: binary
<Contents of ZIP File>
In all of the examples I've seen they put the file in CURLOPT_POSTFIELDS but I don't know how to combine that with json_encode and the above request looks like the file is sent in a separate part of the request.
Thanks!
Split the data into two fields:
$postdata = array(
'json' => json_encode($whatever),
'zipfile' => '#/path/to/yourfile.zip'
);
curl_setopt($curl, CURLOPT_POST_FIELDS, $postdata);
Then on the receiving end:
$json = json_decode($_POST['json');
$file = $_FILES['zipfile'];
I am trying to send JSON data from a form using the XMLHttpRequest object. I can send the data using the following function. There are no errors displayed in FireBug and the JSON-data in the request is displayed well formed by FireBug.
However, I send the data to echo.php, what simply returns the content:
<?php
print_r($_POST);
print_r($_GET);
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
echo file_get_contents('php://input');
?>
The POST-array is always empty, but I can see the JSON string returned by file_get_contents. How does that happen? What am I doing wrong?
output of echo.php
Array
(
)
Array
(
)
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Referer: http://localhost/form.html
Content-Length: 88
Cookie: {{..to much data..}}
Pragma: no-cache
Cache-Control: no-cache
{"type":"my_type","comment":"commented"}
the sending function:
function submit(){
var data={};
data.type=document.form.type.value;
data.comment=document.form.comment.value;
//get right XMLHttpRequest object for current browsrer
var x=ajaxFunction();
var string = JSON.stringify(data);
x.open('POST','echo.php',true);
x.setRequestHeader('Content-type','application/json; charset=utf-8');
x.setRequestHeader("Content-length", string.length);
x.setRequestHeader("Connection", "close");
x.onreadystatechange = function(){
if (x.readyState != 4) return;
if (x.status != 200 && x.status != 304) {
alert('HTTP error ' + req.status);
return;
}
data.resp = JSON.parse(x.responseText);
if(data.resp.status=='success'){
alert('That worked!');
}else{
alert('That didn\'t work!');
}
}
x.send(string);
return false; //prevent native form submit
}
PHP does not process JSON requests automatically like it does with form-encoded or multipart requests. If you want to use JSON to send requests to PHP, you're basically doing it correctly with file_get_contents(). If you want to merge those variables into your global $_POST object you can, though I would not recommend doing this as it might be confusing to other developers.
// it's safe to overwrite the $_POST if the content-type is application/json
// because the $_POST var will be empty
$headers = getallheaders();
if ($headers["Content-Type"] == "application/json")
$_POST = json_decode(file_get_contents("php://input"), true) ?: [];
Quick note: you should not be sending a charset with your Content-Type for application/json. This should only be sent with text/* Content-Types.
You forgot to name your variables in the send function.
The good way to use it is
x.send('name1='+string+'&name2=value2');
Given that, I think you will have to change the content-length header. I don't think it is usefull to send it.
One another thing you can do is try with GET method.
You can also try to change your content-type header by that one :
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")