PHP cURL JSON Object formatting issues - php

I'm running into an issue with formatting using the curl_setopt functions in PHP. I'm basically trying to re-create the cURL request below, but my code returns a bad request from the server. I'm pretty sure it has to do with poor formatting, but I can't figure out where I went wrong.
//This code returns the data back successfully
curl -H "Content-Type: application/json" -d '{"bio_ids": ["1234567"]}' http://localhost:9292/program
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>

There are two issues:
You need to make sure that the structure of $bio matches what you are expected to pass, so the $bio declaration needs to be:
$bio = array('bio_ids' => array('1234567'));
Secondly you need to json_encode this data structure before sending it to the server:
CURLOPT_POSTFIELDS => json_encode($bio),

<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$bio = json_encode($bio);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>

Related

PHP curl PUT does not continue respectively send payload/data

I need to PUT some json data to an API endpoint, which works as expected via command line curl, but not via php curl and I don't have any idea, why it doesn't.
my command is
curl -v --insecure --request PUT --url <https://blabla/blablabla> --user 'username:password' --header 'Content-Type: application/json' --data '<valid json data>'
but it doesn't work this way within php:
// get cURL resource
$curl = curl_init();
// set cURL options
$curloptions = array(
CURLOPT_PUT => true, // set method to PUT
CURLOPT_RETURNTRANSFER => true, // return the transfer as a string
CURLOPT_VERBOSE => true, // output verbose information
CURLOPT_SSL_VERIFYHOST => false, // ignore self signed certificates
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERNAME => $config['uag']['user'], // set username
CURLOPT_PASSWORD => $config['uag']['pass'], // set password
CURLOPT_HTTPHEADER => array( // set headers
"Content-Type: application/json",
),
CURLOPT_POSTFIELDS => $jsondata // set data to post / put
);
curl_setopt_array($curl, $curloptions);
foreach($serverurilist as $uri) {
// set url
curl_setopt($curl, CURLOPT_URL, $uri);
// send the request and save response to $response
$response = curl_exec($curl);
// stop if fails
if(!$response) {
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
var_dump($response);
}
// close curl resource to free up system resources
curl_close($curl);
What doesn't work? The payload / data doesn't get submitted. If I tcpdump the command line und php version without encryption, I can see, that the command line submits the data right after the Expect: 100-continue request and the HTTP/1.1 100 Continue response from the server. The php version doesn't do anything after the HTTP/1.1 100 Continue response and quits after reaching the timeout.
From documentation:
CURLOPT_PUT - true to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
and you are not using any file to provide content.
You should use CURLOPT_CUSTOMREQUEST => 'PUT'.
This is your same cUrl request exported from Postman:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://blabla/blablabla',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS =>'<valid json data>',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='
],
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
You should use this CURLOPT_CUSTOMREQUEST=>'PUT'

Using CURL to receive data, then send data to external webhook

so I am trying to receive JSON data from one webhook, use PHP to filter for some conditions, and then send the data to an external webhook address based on those conditions.
So for example, I created a php file on my server called "webhook.php":
$dataReceive = file_get_contents("php://input");
$dataEncode = json_encode($dataReceive, true);
print_r($dataEncode);
$curl = curl_init();
$opts = array (
CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $dataEncode,
CURLOPT_HTTPHEADER => array (
'Content-type: application/json'
)
);
curl_setopt($curl, $opts);
$results = curl_exec($curl);
echo $results;
curl_close($curl);
The "php://input" can either be exactly as it is, or I tried replacing it with the URL of my webhook.php file just in case. I can test my webhook using Postman, and I am returned a 200 OK, but the data is never sent to my external webhook (https://hooks.zapier.com/hooks/catch/).
I have written the conditional PHP code yet; I just want to ensure I can send and receive this data properly first. Any guidance is much appreciated!
Problem is with curl_setopt. You need to pass three argument for this method curl_setopt ( resource $ch , int $option , mixed $value ). You can set these by following
$curl = curl_init();
$opts = array (
CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $dataEncode,
CURLOPT_HTTPHEADER => array (
'Content-type: application/json'
)
);
foreach ($opts as $key => $value) {
curl_setopt($curl, $key, $value);
}
$results = curl_exec($curl);
echo $results;
curl_close($curl);
Or you can set them individually like this
curl_setopt($curl, CURLOPT_URL, 'https://hooks.zapier.com/hooks/catch/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
.....

Not getting expected PHP cURL response

I have the following PHP code:
<?php
$data = array("client_id" => "sipgate-app-web", "grant_type" => "password", "username" => "my_username", "password" => "my_password");
$data_string = json_encode($data);
$ch = curl_init('https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token');
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/x-www-form-urlencoded',
'Accept: application/json'
));
$result = curl_exec($ch);
echo $result;
?>
Unfortunately, I'm not getting the expected response. The response I'm receiving is:
{"error":"invalid_request","error_description":"Missing form
parameter: grant_type"}
When using an online cURL tool like https://onlinecurl.com with the same data (URL, header, data) as in my cURL PHP code, I'm getting the right response. This means, there's something wrong with my PHP code. I'm not getting any error in the PHP error log.
The manual says I have to use the following cURL code:
curl \
--request POST \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Accept: application/json' \
--data-urlencode "client_id=sipgate-app-web" \
--data-urlencode "grant_type=password" \
--data-urlencode "username=my_username" \
--data-urlencode "password=my_password" \
https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token
Since I'm new to cURL, after googling a lot, I have no idea what I'm doing wrong.
Can anybody help me?
EDIT: You can test my PHP code above as it is. You should get the following response, if the code is working:
{"error":"invalid_grant","error_description":"Invalid user
credentials"}
As per the manual, your request needs to have the Content-Type of application/x-www-form-urlencoded which looks like this:
key1=value1&key2=value2
Thus you need to convert your array into such a string either manually or with http_build_query, like so:
$data_string = http_build_query( $data );
I am consuming one of the API using following PHP CURL, Give this a try and pass your credentials i.e username and password in "your username" and "your password".
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sipgate.com/login/sipgate-apps/protocol/openid-
connect/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"{\r\n\client_id:\"sipgate-app-
web\",\r\n\tgrant_type\"password\",\r\n\tusername:\"your
username\",\r\n\tpassword:\"your password\"\r\n}",
CURLOPT_HTTPHEADER => array(
"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;
} ?>

PHP cURL - authorization token missing

I am trying to cURL apptweak (ref - https://apptweak.io/api )
curl -H 'X-Apptweak-Key: your-api-key' https://api.apptweak.com/ios/applications/284882215.json
I have my key and can curl from the terminal. In PHP, I get "authorization token missing".
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.apptweak.com/ios/applications/284882215.json&country=US&language=en',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
X-Apptweak-Key => 'MY-KEY-IS-HERE'
)
));
$resp = curl_exec($curl);
print $resp;
curl_close($curl);
Is X-Apptweak-Key => 'MY-KEY-IS-HERE' being a POST field the issue here?
What is wrong?
you can add X-Apptweak-Key between single quotes it's a key
CURLOPT_POSTFIELDS => array(
'X-Apptweak-Key' => 'MY-KEY-IS-HERE'
)
or you can try this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic MY-KEY-IS-HERE'));
or you can use:
curl_setopt($ch, CURLOPT_USERPWD, "X-Apptweak-Key:MY-KEY-IS-HERE");

How to connect to the new assembla key?

The new assembla api provides by REST-access a new authentification. i would like connect with PHP and curl, but I am not sure how I can include the api-x-key and api-x-secret as options:
The invoke with curl in terminal:
curl -H "X-Api-Key: XXX" -H "X-Api-Secret: XXX" https://api.assembla.com/v1/spaces/XXX/tickets.json
in PHP (my problem):
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => ' https://api.assembla.com/v1/spaces/XXX/tickets.json',
CURLOPT_POSTFIELDS => ???maybe???
));
$response = curl_exec($ch);
print_r($response);
This is my first try, without the options from api-key/api-secret including.
Send those keys as headers. Try this:
$headers = array('X-Api-Key: YOUR_KEY',
'X-Api-Secret: YOUR_SECRET'
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => ' https://api.assembla.com/v1/spaces/XXX/tickets.json',
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($ch);
print_r($response);
Hope this helps.
Assembla API in PHP:
$headers = array('X-Api-Key: YOUR_KEY',
'X-Api-Secret: YOUR_SECRET'
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => ' https://api.assembla.com/v1/spaces/XXX/tickets.json',
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($ch);
print_r($response);
This code prints a blank page.
No response
help required please

Categories