I have a device where I execute this php file
$url = "https://xxxxx.com/raspberry/json.php";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = <<<DATA
{
"Device": "102",
"Status": "Power on",
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
The receiver file
$data = file_get_contents('php://input');
echo $data;
$json = json_decode($data, true);
echo "Device: " . $json['Device'];
echo "Device: " . $json->Device;
print me
string(62) "{
"Device": "125",
"Status": "Power on",
}Device: Device: "
so why don't print me the single data? I expect it prints also the single element.
thanks
this is the correct files.
// SEND DATA
$url = "https://xxxx.com/raspberry/json.php";
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'Device' => '125',
'password' => 'Power on'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
and receive the data
// RECEIVE DATA
//Make sure that it is a POST request.
if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) {
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if (strcasecmp($contentType, 'application/json') != 0) {
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if (!is_array($decoded)) {
throw new Exception('Received content contained invalid JSON!');
}
// Access to the data
$element = $decoded['Device'];
echo "Device: " .$element;
thanks to Will B.
Related
I'm trying to get the data from pull service in PHP while i"m calling the end point in postman I'm getting the output
but while I'm trying to call using PHP I'm getting the 500
i have attaching the PHP code please guide me where I'm doing wrong
//API Url
$url = 'https://abc.xyz/vlet?Info=';
//The JSON data.
$jsonData =
array(
'NAME' => 'anish',
'Key' => 'vQOgCmDgxxdw',
'authToken' => 'xswSgsG8Dtz05Rfhfzr83t25',
'work_date' => '2020-07-07'
);
//print_r( $jsonData); exit;
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
$full_url = $url.$jsonDataEncoded ;
//echo $full_url ;
$result1 = file_get_contents($full_url);
print_r( $result1);
//Initiate cURL.
$curl = curl_init();
$ch = curl_setopt($curl, CURLOPT_URL, $full_url);
//$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
print_r($result);
I am working with PHP curl for post, for some reason I couldn't post the form successfully.
$ch = curl_init();
$headers = [
'x-api-key: XXXXXX',
'Content-Type: text/plain'
];
$postData = array (
'data1: value1',
'data2: value2'
);
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
When I try using the same in post it works, but not with PHP.
var_dump($server_output) ==> string(67) ""require data1 and data2 or check the post parameters""
var_dump(curl_error($ch)) ==> string(0) ""
If you wanna use Content-type: application/json and raw data, seem your data should be in json format
$ch = curl_init();
$headers = [
'x-api-key: XXXXXX',
'Content-Type: application/json'
];
$postData = [
'data1' => 'value1',
'data2' => 'value2'
];
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
If you want an arranged and explained format, see the code below.
// Set The API URL
$url = 'http://www.example.com/api';
// Create a new cURL resource
$ch = curl_init($url);
// Setup request to send json via POST`
$payload = json_encode(array(
'data1' => 'value1',
'data2' => 'value2'
)
);
// 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('x-api-key: XXXXXX', 'Content-Type: application/json'));
// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request
$result = curl_exec($ch);
// Get the POST request header status
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// If header status is not Created or not OK, return error message
if ( $status !== 201 || $status !== 200 ) {
die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}
// Close cURL resource
curl_close($ch);
// if you need to process the response from the API further
$response = json_decode($result, true);
I hope this helps someone
I was following this Tutorial to create A Facebook Messenger bot using php
Everything is working fine, except sender don't receive my message.
there is my code
<?php
$access_token =""; //Token
$verify_token = ""; //Verify Token
$hub_verify_token = null;
if(isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$message_to_reply = "Huh? You are talking to me?";
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
I can receive the message and see it, But the user don't receive back my message.
This is fixed by adding following lines of code before //Execute the request
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Hope it helps.
$jsonData = '{
"messaging_type": "RESPONSE",
"recipient":{
"id": "' . $sender . '"
},
"message":{
"text": "teste web"
}
}';
$s="";
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
I need to send some json data to a url and receive its json response. I am not so good at json, and i searched and found the following code
<?php
$json_data = array(
'partnerid' => '123',
'outletid' => '321',
'mobile' => '0123456789',
'secret' => 'qwert',
'amount' => '100',
);
$json = json_encode($json_data, true);
$req_url = "https://myapiprovider.com/api/requestdata";
//send json request
//Initiate cURL.
$ch = curl_init($req_url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
//receive json response
$content = file_get_contents($req_url);
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
//Process the JSON.
?>
I get the following exception 'Content type must be: application/json'. Why? I have set the content type to application/json. right? Please help immidiate.
$json_data = array(
'partnerid' => '123',
'outletid' => '321',
'mobile' => '0123456789',
'secret' => 'qwert',
'amount' => '100',
);
$json = json_encode($json_data, true);
$req_url = "https://myapiprovider.com/api/requestdata";
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $req_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, count($json));
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl,CURLOPT_POSTFIELDS, $json);
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result);
I have a php script which tries to use google Safe Browsing Lookup API (v4), but I'm getting error "Invalid JSON payload received. Unknown name \"\": Root element must be a message..."
Here is my code:
<?php
$data = '{
"client": {
"clientId": "TestClient",
"clientVersion": "1.0"
},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["LINUX"],
"threatEntryTypes": ["URL"],
"threatEntries": [
{"url": "http://www.google.com"}
]
}
}';
$apikey = "my_secret_api_key";
$url_send ="https://safebrowsing.googleapis.com/v4/threatMatches:find?key=".$apikey."";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", 'Content-Length: ' . strlen($post)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
$jaahas = sendPostData($url_send, $str_data);
echo "<pre>";
var_dump($jaahas);
?>
Is there something wrong with the json-data array formatting or what might be the problem?
You're running json_encode on data which is already encoded.
ie. change this line:
$jaahas = sendPostData($url_send, $str_data);
to
$jaahas = sendPostData($url_send, $data);