How to send and receive data to/from an API using CURL? - php

I have to make an API. For this, I will receive the data from the mobile devices as JSON using POST. I have to work with this data and send the response back to the devices also as JSON.
But I don't know how to take the data that I will receive. I have tried to make some tests using CURL to see how can I take this data but the $_POST is always empty. Can you please tell me how to send the data as JSON format to the API using CURL and how can I receive this data so I can work with it and send it back as response?
These are my test files:
curl.php:
//set POST variables
$url = 'http://test.dev/test.php';
$data = array(
'fname' => 'Test',
'lname' => 'TestL',
'test' => array(
'first' => 'TestFirst',
'second' => 'TestSecond'
)
);
//open connection
$ch = curl_init($url);
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
// execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
test.php:
var_dump($_POST);
The response that I get is:
array(0) { }

You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST array is empty. If you want it, you need do the parsing yourself in the test.php:
$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);
same questions: 1 2

Related

sending json via php curl but not getting a response

I am trying to send a json to a url and get a response back. I am creating the json correctly I believe. However when I try to send it via php curl I do not get a response back. The url I am sending it to does populate a response though.
Here is the php:
<?php
$post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);
$transfer = json_encode($post);
$ctrl = curl_init();
curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
curl_setopt($ctrl, CURLOPT_POST, TRUE);
curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ctrl);
curl_close($ctrl);
$response = json_decode($response);
echo $response;
?>
If I were to echo $transfer it would read:
{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
"output":"4"}
}
I would like to echo the response from the url I am sending the json too but instead, I get nothing back. However the url in the curl sequence (https://sample.com/question/add-question.php) does output a json on the webpage:
{"message":"An unknown internal error occured","success":false}
How am I not able to grab this and echo it in my original code snippet? Is it something wrong with my curl method?
Try setting the header to say you are sending JSON...
curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($transfer))
);
For the HTTPS, you may also need...
curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);
You also may try...
curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1);

Data not being received when sent by CURL

I am sending data via post command of curl. data is sent using array but when i receive, it just contains 1 and 0. Could you tell how to receive data that is being posted by curl.
Heres my code for curl.php file: $data array is being posted
<?php
$data=array(
'product_name' =>'Television',
'price' => 1000,
'quantity' => 10,
'seller' =>'XYZ Traders'
);
$url = 'http://localhost/API2/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
echo $response_json;
curl_close($ch);
?>
i am trying to get the posted data from curl in my products.php file using $_POST. But i receive one's and zero's
echo"Got here ";
$_product_name=$_POST["product_name"];
$_price=$_POST["price"];
$_quantity=$_POST["quantity"];
$_seller=$_POST["seller"];
echo"data:= "+$_product_name+$_price+$_quantity+$_seller;
So is it the right way to get data out of array being sent from curl or do i need to loop through array.

PHP Curl Send JSON Data

I am following this tutorial:
https://lornajane.net/posts/2011/posting-json-data-with-php-curl
what I am trying to do is POST JSON Data through CURL
$url = "http://localhost/test/test1.php";
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-type: application/json", "Content-Length: " . strlen($data_string)));
$result = curl_exec($ch);
var_dump($result);
when I POST plain text data , I am able to receive that, but when I try through JSON , I am not able to receive that.
Here is my test1.php
test1.php
print_r($_POST);
print_r($_POST);
Any help would be appreciated.
Thanks
When you POST JSON Data through cURL, you have to use php://input. You can use it like:
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
return json_decode($rawData, true); // will return array
php://input is a read-only stream that allows you to read raw data
from the request body
The PHP superglobal $_POST, only is supposed to wrap data that is either
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST -wrapper doesn't know how to handle that (yet).
Reference
JSON data does not come through in $_POST. You need to use file_get_contents('php://input');
You will also need to json_decode it.
$json = json_decode(file_get_contents('php://input'));
var_dump($json);

PHP Api Receiving JSON data

I am trying to make an API with PHP and JSON, however I am stuck on extracting the JSON on the receiving/API side of the request.
So I am doing this on the client end of my transaction:
$data = array("test" => "test");
$data_string = json_encode($data);
$ch = curl_init('https://..../api/v1/functions? key=TPO4X2yCobCJ633&aid=9&action=add');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$return = curl_exec($ch);
But how do I receive and extract the POSTed data on the server (receiving) side of the transaction (inside my API)?
Summary:
What i mean is i have a client that is sending a JSON file to the API now i what i don't understand is how can i get the API side to see and extract/see the data
On the receiving side you need to read from the PHP input stream, then decode:
<?php
// read the incoming POST body (the JSON)
$input = file_get_contents('php://input');
// decode/unserialize it back into a PHP data structure
$data = json_decode($input);
// $data is now the same thing it was line 1 of your given sample code
If you wanted to be more succinct, you could obviously just nest those calls:
<?php
$data = json_decode(file_get_contents('php://input'));

Convert URL encoded to JSON object

I've never worked with JSON objects before but I think this is probably the best route for what I'm trying to achieve (if you think there is a better option please let me know, though I cannot use SOAP)
I am trying to submit some data via POST to an API in order to add some data to a newsletter list which is stored as XML. Here is the documentation for the request I am trying to complete: https://api.dotmailer.com/v2/help/wadl#PostAddressBookContacts
When visiting the API url and authenticating I see data laid out in the following:
<ArrayOfApiContact xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://apiconnector.com">
<ApiContact>
<Id>1058905201</Id>
<Email>email#email.co.uk</Email>
<OptInType>Unknown</OptInType>
<EmailType>Html</EmailType>
<DataFields i:nil="true"/>
<Status>Subscribed</Status>
</ApiContact>
</ArrayOfApiContact>
So I have attempted to replicate as such, using a variable instead of a hardcoded email:
$xml = array(
'id' => urlencode('123456789'),
'email' => urlencode($useremail),
'optInType' => urlencode('Unknown'),
'emailType' => urlencode('Html'),
'dataFields' => urlencode(':null'),
'status' => urlencode('Subscribed')
);
I am combining the array here:
foreach($xml as $key=>$value) { $xml_string .= $key.'='.$value.'&'; }
And then using cURL to POST the request to the API, with my authentication (apipassword and apiemail which the username)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$auth_url);
curl_setopt($ch,CURLOPT_POST, count($xml));
curl_setopt($ch,CURLOPT_POSTFIELDS, $xml_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$apiemail:$apipassword");
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
$result = curl_exec ($ch);
curl_close ($ch);
I have already tested this without the POST and I do indeed get the data back in this form:
[{"id":1058905201,"email":"email#email.co.uk","optInType":"Unknown","emailType":"Html","dataFields":null,"status":"Subscribed"}]
So I know the auth is working and the data is coming back correctly, but now when I try to POST my data I get:
{"message":"Content type \"application/x-www-form-urlencoded\" is not supported. Please use one of: application/json,application/xml ERROR_CONTENT_TYPE_IS_NOT_SUPPORTED"}
So how do I convert my array which is URL encoded into something readable by the API?
Try a content type of application/json like so:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json'));
Two things here (a) content-type header JSON missing and (b) payload not JSON.
// setup request to send json via POST.
$payload = json_encode(array("json"=> $data)); // or json_encode(array($data));
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
// set proper content-type for sending JSON
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

Categories