Send json post using php
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Send JSON data via POST to PHP
This is how I did with AJAX request to send json data to my URL:
var dataToSend = {
name: "Nicolas",
age: 24,
sex: "Male"
}
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type:'POST',
url: "/your-url",
data: jsonDataToSend,
success:function(data){
console.log("success");
},
error: function (data) {
console.log("error");
}
});
And how to receive this posted data in request handler on PHP side:
$postbody = $request->json()->all();
$name = $postbody['name'];
$age = $postbody['age'];
$sex = $postbody['sex'];
Sending a JSON POST request to REST API in PHP
Your json_encode requires an array.
It should look like this
<?php
$checkfor = ([
'serverId'=>'Server',
'featureId'=>'Feature',
'propertyId'=>'Property'
]);
$checkforJson = json_encode($checkfor);
var_dump($checkforJson); // this will now work
https://3v4l.org/RG5Zv
For better understanding read doc
UPDATE I also notice on the curl script, your array needs fixed again
$body['serverId'] = 'Server';
and dont json encode the post fields afterwards, it takes an array.
Send POST data via raw JSON with Postman
Unlike jQuery
in order to read raw JSON
you will need to decode it in PHP.
print_r(json_decode(file_get_contents("php://input"), true));
php://input
is a read-only stream that allows you to read raw data from the request body.
$_POST
is form variables, you will need to switch to form
radiobutton in postman
then use:
foo=bar&foo2=bar2
To post raw json
with jquery
:
$.ajax({
"url": "/rest/index.php",
'data': JSON.stringify({foo:'bar'}),
'type': 'POST',
'contentType': 'application/json'
});
POST request with JSON body
You need to use the cURL library to send this request.
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Close the cURL handler
curl_close($ch);
// Print the date from the response
echo $responseData['published'];
If, for some reason, you can't/don't want to use cURL, you can do this:
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
// http://www.php.net/manual/en/context.http.php
'method' => 'POST',
'header' => "Authorization: {$authToken}\r\n".
"Content-Type: application/json\r\n",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
How to send post json object in php?
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => json_encode($data)
)
);
$fp = fopen('http://url', 'r', false, $context_options);
how to send a json request in php?
According to your Error, it seems your service did not respond. Have you tried to open it in a browser, to check if any response there?
Maybe the service you try to call requires you to provide a Static IP from your Webserver, as they only grant access on a IP based level. Means, your IP is blocked until they allow it.
I suggest you use cURL to do your request. This way you get future data to use for debugging, if anything fails. Still here, if the service does not respond, you want get any other information.
$data = array(
'mobileNo' => '****',
'service' => '***',
'Code1' => '*****',
'content' => '55',
'actionDate' => '2017/09/26');
$url = "******";
$ch = curl_init( $url );
// set data as json string
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
// define json as content type
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// tell curl to fetch return data
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// follow location if redirect happens like http to https
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
// send request
$result = curl_exec($ch);
// gives you the result - most of the time you only want this
var_dump($result);
// for debugging purpose, gives you the whole connection info
var_dump(curl_getinfo($ch));
// gives back any occurred errors
var_dump(curl_error($ch));
curl_close($ch);
Edit: I added the CURLOPT_FOLLOWLOCATION, as a request may gets redirected. We want to catch that as well. And I added the curl_close at the end. If it is closed, error or info data can be fetched.
Related Topics
Paypal Access - Ssl Certificate: Unable to Get Local Issuer Certificate
Creating a Thumbnail from an Uploaded Image
Generating (Pseudo)Random Alpha-numeric Strings
Making Sure PHP Substr Finishes on a Word Not a Character
Convert Plain Text Urls into HTML Hyperlinks in PHP
MySQL Check If a Table Exists Without Throwing an Exception
Execute PHP Scripts Within Node.Js Web Server
Are There Good Tutorials on How to Use Pdo
How to Change Public Folder to Public_Html in Laravel 5
How to Find Out How "Deep" a PHP Array Is
The Character Encoding of the HTML Document Was Not Declared
How to Check Whether the User Uploaded a File in PHP
How to Write a File in Utf-8 Format
How to Upload & Save Files With Desired Name
Connect PHP to Mssql Via Pdo Odbc
Accessing Outside Variable Using Anonymous Function as Params