send multiple json data into api - php

I want to send these three array data into the external api. For that firstly I encode this into JSON, but always it sends the last array.
$params = array( array('receiverName' => 'sample_name',
'receiverEmail' => 'krishanuniyalas#gmail.com',
'senderEmail' => 'info#hotelpalacio.net',
'roomNumber' => '12456',
'accessToken' =>'ca5629d0-6810-11e8-9d40-d7194ac0ac8d'),array('receiverName' => 'sample_name',
'receiverEmail' => 'karamuniyalas#gmail.com',
'senderEmail' => 'info#hotelpalacio.net',
'roomNumber' => '12456',
'accessToken' =>'ca5629d0-6810-11e8-9d40-d7194ac0ac8d'),array('receiverName' => 'sample_name',
'receiverEmail' => 'krishanuniyalas#gmail.com',
'senderEmail' => 'info#hotelpalacio.net',
'roomNumber' => '12456',
'accessToken' =>'ca5629d0-6810-11e8-9d40-d7194ac0ac8d'));
$data_string = json_encode($params);
foreach($params as $pa) {
$r=json_encode($pa);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $r);

Here 's a working example ...
$data = [
[
'a' => 'bla',
],
[
'b' => 'blubb',
],
];
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, "http://www.example.com/");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$result = [];
foreach ($data as $value) {
$json = json_encode($value);
curl_setopt($handle, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
]);
$result[] = curl_exec($handle);
}
Open a valid curl resource and set the corresponding curl options for your purpose. You want to send a json string as post request. Furthermore you should tell the other side, that you send json data. Say curl, that you 're awaiting a response and the fire every time running through the foreach loop. That 's all ...
If you want to send the whole data at once leave out the foreach loop end encode the whole data array and send it.

You need to just create a simple query params like $data = http_build_query($params)
And then pass data to your curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

Related

How to decode response of eth_getlogs with PHP?

I succeeded in getting the contract log from infura with eth_getlogs.
But I don't know how to decode the retrieved data with PHP.
Please tell me how to decode retrieved data with PHP.
PHP code
$my_server_url = "https://mainnet.infura.io/v3/APIKey";
$ch = curl_init($my_server_url);
$data = array(
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'eth_getLogs',
'params' => array(array(
"fromBlock" => "0x949986",
"toBlock" => "latest",
"topics" => ["0x70d79747edd06ece6bf0a5ee4429d0138fa4ccbeefaea4d21e0e511e9d81b094"],
"address" => "0xf0A0293D762aF2AC36E57613D42aC36773eEAf51"
))
);
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
Retrieved Data:
{"jsonrpc":"2.0","id":1,"result":[{"address":"0xf0a0293d762af2ac36e57613d42ac36773eeaf51","blockHash":"0x348b7e3dcf6c76c483f872851650b7aed8f2f6d6042207b8f55e13a6c52a19cd","blockNumber":"0x949986","data":"0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000973616d706c653132330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6372656174652073756363657373000000000000000000000000000000000000","logIndex":"0x85","removed":false,"topics":["0x70d79747edd06ece6bf0a5ee4429d0138fa4ccbeefaea4d21e0e511e9d81b094","0x0000000000000000000000008790dc53157f7090b85785fc107360a23ad63a13"],"transactionHash":"0x0b9544631e221ed9569aae363d272a54dc853cf7f84610bda3c828c6f181784e","transactionIndex":"0x4a"},{"address":"0xf0a0293d762af2ac36e57613d42ac36773eeaf51","blockHash":"0xc287eb38486a137e33a85f641efdcc1f57b90d3f7889709503e53fec54657ff0","blockNumber":"0x9499f2","data":"0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000973616d706c65313233000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000137365742061646472657373207375636365737300000000000000000000000000","logIndex":"0x60","removed":false,"topics":["0x70d79747edd06ece6bf0a5ee4429d0138fa4ccbeefaea4d21e0e511e9d81b094","0x0000000000000000000000008790dc53157f7090b85785fc107360a23ad63a13"],"transactionHash":"0xae01b5c746ce2229c566682208b7af1f0520e094dfc2adef69f22eb8dd6f3bf2","transactionIndex":"0x4a"}]}
I want to decode data section of retrieved data.

cURL Redirect Returned URL

I want to send data from site A to site B. I've successfully transferred data but I want to redirect the url to the returned url generated from Curl. Below is my code.
$jsonData = array(
'first_name' => "$fname",
'last_name' => "$lname",
'phone_number' => "$phone",
'gender' => "$gender",
'email' => "$email",
'businessname' => "$businessname",
'natureofbusiness' => "$biznature",
'address' => "$address",
'utm' => "esg",
'date' => "$d"
);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
This is the result
{"data":{"success":true,"redirectUrl":"https://url.com/authorize
/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODU5MDg4MzgsImRhdGEiOnsidXRtIjoiZXNnIiwiZW1haWwiOiJjbm5lYnVlNGFsbEB5YWhvby5jb20iLCJmaXJzdE5hbWUiOiJDaGlt
YSIsImxhc3ROYW1lIjoiT3NjYXIiLCJjb250YWN0TnVtYmVyIjoiOTg3MzczNjM3MyIsInRpbWVTdGFtcCI6IjE1ODU5MDc4NTUifSwiaWF0IjoxNTg1OTA4NTM4fQ.v6ecH7Tu5WB0ZkK-
U2ob_sQRSNn13rOU95Zo4BgwSF4?utm=esg","status":200}}
I need help to redirect to that Url.
Convert JSON result into array
$result = '{"data":{"success":true,"redirectUrl":"https://url.com/authorize/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODU5MDg4MzgsImRhdGEiOnsidXRtIjoiZXNnIiwiZW1haWwiOiJjbm5lYnVlNGFsbEB5YWhvby5jb20iLCJmaXJzdE5hbWUiOiJDaGltYSIsImxhc3ROYW1lIjoiT3NjYXIiLCJjb250YWN0TnVtYmVyIjoiOTg3MzczNjM3MyIsInRpbWVTdGFtcCI6IjE1ODU5MDc4NTUifSwiaWF0IjoxNTg1OTA4NTM4fQ.v6ecH7Tu5WB0ZkK-U2ob_sQRSNn13rOU95Zo4BgwSF4?utm=esg","status":200}}';
$result = json_decode($result, true);
Now get url from array.
if(isset($result["data"])){
if($result["data"]["success"]==true){
$url = $result["data"]["redirectUrl"];
header("location:".$url);
}
}

Slack sends invalid, mal-formed JSON data after Dialog interaction

I am working on a slash command that'll invoke a dialog.
$dialog = [
'callback_id' => 'ryde-46e2b0',
'title' => 'Request a Ride',
'submit_label' => 'Request',
'elements' => [
[
'type' => 'text',
'label' => 'Pickup Location',
'name' => 'loc_origin'
],
[
'type' => 'text',
'label' => 'Dropoff Location',
'name' => 'loc_destination'
]
]
];
// get trigger ID from incoming slash request
$trigger = filter_input(INPUT_POST, "trigger_id");
// define POST query parameters
$query = [
'token' => 'XXXXXXXXX MY TOKEN XXXXXXXXX',
'dialog' => json_encode($dialog),
'trigger_id' => $trigger
];
// define the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
var_export($response);
When I issue the slash command, my test dialog opens successfully
I then fill two test values test1 and test2 in the fields and submit the request. My endpoint is being hit with the dialog data payload correctly, but the data sent is not valid JSON:
The value of $_POST is: (I've masked all identifying tokens/IDs with xxx)
{"payload":"{\\\"type\\\":\\\"dialog_submission\\\",\\\"token\\\":\\\"XXX\\\",\\\"action_ts\\\":\\\"1536603864.688426\\\",\\\"team\\\":{\\\"id\\\":\\\"xxx\\\",\\\"domain\\\":\\\"ourdomain\\\"},\\\"user\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"my_name\\\"},\\\"channel\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"directmessage\\\"},\\\"submission\\\":{\\\"loc_origin\\\":\\\"test1\\\",\\\"loc_destination\\\":\\\"test2\\\"},\\\"callback_id\\\":\\\"ryde-46e2b0\\\",\\\"response_url\\\":\\\"https:\\\\/\\\\/hooks.slack.com\\\\/app\\\\/XXX\\\\/XXX\\\\/XXX\\\",\\\"state\\\":\\\"\\\"}"}
This is an invalid JSON, even when the "\\" instances are removed. Why is this happening?
Here is the code that handles the POST from Slack:
error_log(" -- dialog response: " . json_encode($_POST) . "\n", 3, './runtime.log');
Which results in the output above.
I'm not sure why you are calling json_encode($_POST). The documentation is very clear on the format that will be sent:
$payload = filter_input(INPUT_POST, 'payload');
$decoded = json_decode($payload);
var_dump($decoded);

Multiple records in json and array, and txt reading?

im trying to send to my api site, the following Json with one record.
It works Ok, but I want to send more than one record, how can I do that?
Later i want to read a txt and make a json with all the records in it.
<?php
//API URL
$url = 'http://mysitexder.net/receiveJson.php';
//create a new cURL resource
$ch = curl_init($url);
//setup request to send json via POST
$data = array(
'cod' => '321',
'name' => 'Jane',
'address' => 'Route 123456'
);
$payload = json_encode(array("user" => $data));
//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute the POST request
$result = curl_exec($ch);
//close cURL resource
curl_close($ch);
Send a 2-dimensional array:
$data1 = array(
'cod' => '321',
'name' => 'Jane',
'address' => 'Route 123456'
);
$data2 = array(
'cod' => '555',
'name' => 'John',
'address' => '123 Main St'
);
$payload = json_encode(array('users' => array($data1, $data2)));
Later i want to read a txt and make a json with all the records in it.
It's hard to tell what you mean by this. But you should parse the text in whatever way you want (e.g. each line is a record), create a PHP array from that, and call json_encode().

How can I forward $_POST with PHP and cURL?

I receive a POST request at my PHP script and would like to forward this POST call to another script using POST too. How can I do this?
I can use cURL if it's required for this action.
Perhaps:
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
From curl_setopt:
This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
Do this,
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($_POST));
Here's a fully functional cURL request that re-routes $_POST where you want (based on ZZ coder's reply)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://urlOfFileWherePostIsSubmitted.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// ZZ coder's part
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
$response = curl_exec($ch);
curl_close($ch);
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If need any HTTP authentication
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This can be $arrPostData = $_POST;
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your POST data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // ONLY use this when requesting JSON data
$arrResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // ONLY use this when request json data
),
// If HTTP authentication is required , use the below lines
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));

Categories