I'm using the following code to POST. However, the contents of $_POST are null. What am I missing here?
$orderData = "This is an order";
$json = json_encode($orderData);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost:9999/printpost.php",
CURLOPT_CAINFO => "C:\MAMP\conf\php7.0.0\cacert.pem",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"authorization: ".$oauthToken,
"content-type: application/json",
"programid: ".$programId
),
CURLOPT_POSTFIELDS => $json
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The $_POST superglobal is only used for Content-Type: application/x-www-form-urlencoded; i.e. key/value pairs formatted like foo=1&bar=2. You're posting JSON. Consume it like this on the server side instead of using the superglobal:
$json = file_get_contents('php://input');
Additionally, I recommend the following changes in the cURL client code you posted:
Replace
CURLOPT_CUSTOMREQUEST => "POST",
with
CURLOPT_POST => 1,
And add
CURLOPT_RETURNTRANSFER => 1,
The POST data should not be encoded as JSON, it should be a URL-encoded string in the form name=value&name=value&.... Furthermore, even if JSON were processed, you didn't specify a name for your parameter, so what were you expecting the key in $_POST to be?
If you provide an associative array as CURLOPT_POSTFIELDS, it will automatically encode it for you.
'CURLOPT_POSTFIELDS' => array('orderData' => $orderData)
Then in the server script you can use $_POST['orderData']
Related
I'm currently trying to get every title of my JSON decoded output in a variable
This is what works for me as curl
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://api.irail.be/disturbances/?format=json&lang=nl',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'cache-control: no-cache',
'content-type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
// Decode JSON response and get only the data needed:
$response = json_decode($response);
$response = $response->disturbance[0];
var_dump($response);
$name = $response->title;
echo $name;
When I remove the [0] behind disturbance I am getting a blank $name. Does anyone know how I can fix this?
Thank you
You can access your objects via the keys, but "disturbance" is not a key, it is a value that the key type can take.
You need first to filter your data to get only the items with type = 'disturbance', and then you can get the titles.
Here is an example :
$response = json_decode($response);
$disturbanceItems = array_filter($response, function ($item){return $item->type == 'disturbance';});
echo $disturbanceItems[0]->title ;
I use postman for the first time.
My goal is to download a JSON file.
I managed to look at the code for cURL in postman:
But if I test the code in the command line, I can not log in.
Actually, I want to call the JSON file via PHP. I have tested initial approaches. In addition to the problem that I can not authenticate myself here, I think that I need more values. For example POSTFIELDS. Is that correct and if so, how do I find what I have to enter in Postman? Here is my initial Code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.divessi.com/divessi/index.php",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "..",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic BASE64",
"Cache-Control: no-cache",
"Postman-Token: TOKEN",
"content-type: ??"
),
));
$response = curl_exec($curl);
$obj = json_decode($response);
$events = array();
if ($obj)
{
$events = $obj[0]->DATA;
}
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
} else {
foreach ($events as $event) {
...
}
I have 2 json response from 2 different urls, the first step one if user fill the customernumber with post method to get the billNo value as below:
{
"Customer":[
{
"billNo":"1001337"
}
],
}
The second one to another url user fill the billNo (got from the first step above) in a form with post method to get details result response like this:
{
"Billing":[
{
"billAccName":"John Doe",
"billAccStatus":"Active"
}
],
}
My question is it possible to combine this result with only using first step only fill up the customernumber? Within the expected result is:
{
"Billing":[
{
"billAccName":"John Doe",
"billAccStatus":"Active"
}
],
}
I am using Curl with PHP to get those responses, is there any other way to achieve this, maybe need to insert to the temp DB table first?
Edited add the script.
<form class="form-response" method="POST" action="postform.php">
<h2 class="form-response-heading">get Response</h2>
<input name="customernumber" class="form-control" type="text" autofocus="" required="" placeholder="phonenumber"customernumber">
<button class="btn btn-lg btn-primary btn-block" type="submit">Get Response</button>
</form>
<?php
$customernumber = $_POST['customernumber'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"customernumber\":\"" .$customernumber . "\"}",
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikeynumbers",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Update Script:
<?php
$phone = $_POST['customernumber'];
$curl = curl_init();
$data = array("customernumber" => $phone);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikey",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$result = json_decode($response);
$billno = $result->Customer[0]->billNo;
//now here, make your second API call using the Bill Number retrieved from the response
$billAccNo = $_POST['billNo'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/getBillingDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"billAccNo\":" .$billAccNo . "}",
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapike",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
Thanks for any suggestions
You just need to programatically retrieve the Bill No from the data returned by the first request, and then put it in a variable to be included in your second request. You can do that by decoding the JSON data into a PHP object and then extracting the correct field from it.
I've assumed that you either only ever get one Customer back from the first request, or that you only ever are interested in the first Customer record returned. If that's not the case you'll have to modify the code accordingly.
Also, you haven't provided the code used to run the second request, so I'll have to leave it to you to use the $billno variable in a suitable way in that request.
The change occurs in the else statement at the bottom of the code, where instead of just echoing the raw response we instead decode it and take the Bill No from it.
<?php
$phone = $_POST['customernumber'];
$curl = curl_init();
$data = array("customernumber" => $phone);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikeynumbers",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$result = json_decode($response);
$billno = $result->Customer[0]->billNo;
//now here, make your second API call using the Bill Number retrieved from the response
}
P.S. I also changed your input JSON data to be created reliably using json_encode. Building JSON by hand, even a simple string like this, is potentially prone to failure due to unexpected syntax errors, typos etc - instead used the tools provided to convert a PHP variable with a known-good structure into a valid JSON string in a reliable, repeatable way.
I have some problem(s) with PHP cURL. I tried to get data from the API using PHP cURL. This is my cURL code in PHP :
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.example.com/dos/AW/API",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"Filter\" : {\"IsActive\" : \"True\",\"OutputSelector\" : \"Name\"}}",
CURLOPT_HTTPHEADER => array(
"API_ACTION: GetItem",
"API_KEY: MHlIARzQqxVpOg2dUxH4q9w7bx3pOL6K",
"Accept: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
With that code I can get a response but the response contains some errors. I also tried using POSTMAN to check, and the API works fine as I got a successful response with the same data. My question is: "Is there anything wrong with my cURL code that would explain why I got an error when I used cURL and I got successful response in POSTMAN "?
I would appreciate if someone could help me with this.
Thank you very much.
given that you aren't showing us the successful postman request, we can't know for sure what errors you make, that said, you are making a couple of obvious mistakes here.
first off, when debugging curl code, use CURLOPT_VERBOSE , it gies you a lot of useful information when debugging your curl requests (and if you did this, you would probably notice how the Postman requests's content-type is completely different from curl's content-type http headers - more on this soon)
second, when you want a POST request, don't use CURLOPT_CUSTOMREQUEST, use CURLOPT_POST.
third, when passing a string to CURLOPT_POSTFIELDS, the content-type implicitly becomes Content-Type: application/x-www-urlencoded, unless you override it. and you are obviously NOT sending x-www-urlencoded data, but JSON-encoded data, so your content-type is all wrong, its supposed to be Content-type: application/json
fourth, you can hardcode the json if you want, but the code looks much prettier if you json_encode it
fifth, don't use setopt / setopt_array without checking the return type.
fixing all that, you'll end up with something like:
function ecurl_setopt_array($ch, array $options) {
if (! curl_setopt_array ( $ch, $options )) {
throw new \RuntimeException ( 'curl_setopt_array failed. ' . curl_errno ( $ch ) . ': ' . curl_error ( $ch ) );
}
}
$curl = curl_init ();
ecurl_setopt_array ( $curl, array (
CURLOPT_URL => "https://www.example.com/dos/AW/API",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode ( array (
'Filter' => array (
'IsActive' => 'True',
'OutputSelector' => 'Name'
)
) ),
CURLOPT_HTTPHEADER => array (
"API_ACTION: GetItem",
"API_KEY: MHlIARzQqxVpOg2dUxH4q9w7bx3pOL6K",
"Accept: application/json",
'Content-Type: application/json'
)
) );
$response = curl_exec ( $curl );
$err = curl_error ( $curl );
curl_close ( $curl );
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Edit: fixed the json data, when i wrote it, i didn't see that isActive is not an actual boolean, but the string literal True - i mistakenly encoded it as a json boolean true instead, sorry, fixed. (although i suspect it's supposed to be a boolean anyway, and that your original code just encodes it wrong, perhaps you should double check isActive's type in the api docs, assuming there is one)
#Antonio, Response you are getting is from the other end, might be you are missing something which restrict the processing of query at other end. try to print http_code, or use curl_getinfo to get complete information.
in case of response code is 200, then you may ask from another end to validate the request.
PS: not able to comment because of repo restrictions.
If I use the following:
$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
echo $homepage;
The data is displayed as follows:
{"user":{"profile":{"Id":{"Label":"User Id","Value":102210},"User":{"Label":"User Name","Value":"tom"}
I tried the following that I discovered on here in another post but the page remains blank other than User:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://www.website.com/api/v1/members/102210",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true); //because of true, it's in an array
echo 'User: '. $response['User']['User Name'];
You're misinterpreting the JSON data. There is no User key in the root of the json object and there is no User Name key inside of that either. When you visualize the JSON, this is what it looks like:
What you seem to be looking for is:
echo 'User: ' . $response['user']['profile']['User']['Value'];
I'm not sure why you'd switch to cURL if the file_get_content method works for you. You should be able to simply do this:
$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
$response = json_decode($homepage, true);
echo 'User: ' . $response['user']['profile']['User']['Value'];