Trouble with POST API using cURL - php

I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?

Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.

Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

Related

I'am getting error while sending SOAP web service a post requirest with cURL

I am trying to get info with soap web service but it is giving me an error Request format is invalid: multipart/form-data; boundary=------------------------b35e9c9f375db7a5.
$id = $_POST['id'];
$servicepassword = $_POST['servicePassword'];
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://webgov.com.tr/WebService/Kontrol.asmx/PasoSorguKontrol',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'id' => $id,
'servicepassword' => $servicepassword
],
CURLOPT_FOLLOWLOCATION => 1,
));
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
this web service need two variables to work, student id and web service password. and giving xml output. i could not make the code working. i am a newbie btw.
The solution is using CURLOPT_HTTPHEADER. I even make a function with this codes and it solved my problem.
function httpPost($url,$params) {
$postData = '';
foreach($params as $k => $v) {
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}

POST Request PHP with Curl

I'm working on a wordpress project where I have to modify my theme, so I can request a JSON to an external API.
I've been searching through the internet how to do that and a lot of people use CURL.
I must do a POST request, yet I don't know how it works or how to do it.
So far I've got this code running:
$url='api.example.com/v1/property/search/';
$data_array = array(
$id_company => '123456',
$api_token => 'abcd_efgh_ijkl_mnop',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_array);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
echo($result);
I don't know where exactly I should put my authentication info or how does the curl methods work in PHP. Can you guys check it out and help me solve this?
There are some answers out there that would help you, such as this one.
However, WordPress actually has built-in functions to make GET and POST requests (that actually fall back to cURL I believe?) named wp_remote_get() and wp_remote_post(). Clearly in your case, you'll want to make use of wp_remote_post().
$url = 'https://api.example.com/v1/property/search/';
$data_array = array(
'id_company' => 123456,
'api_token' => 'abcde_fgh'
);
$headers = array(
'APIKEY' => 1111111111,
'Content-Type' => 'application/json'
);
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => $headers,
'body' => $data_array,
'cookies' => array()
)
);
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Success! Response:<pre>';
print_r( $response );
echo '</pre>';
}

Using cURL to get JSON from an API returns nothing

I've started making a webpage that uses an API from another website to get phone numbers for verification of websites, which I've gotten working with Python already. However, when I try to use cURL to get the JSON data from the API it returns nothing. The code for the PHP is below.
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$params = array(
'metod' => 'get_number', # misspelt because it is not an english website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX',
);
$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}
curl_close($ch);
print_r($result);`
I expect that when the code is executed on the server it should give all of the JSON from the file, which I can then use later to pick out only certain parts of it to use elsewhere. However the actual results are that it does not print anything, as seen here: https://imgur.com/sdCYhlw
I'm not sure why your code doesn't work, but a simpler alternative could be to use file_get_contents:
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$postdata = http_build_query(
array(
'metod' => 'get_number', # misspelled because it is not an English website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);

I want to recive the error code. by the sms host server in php

i want to receive errors from the sms host server
curl_error curl_errno curl_strerror all these function returns error but not in the way i want , mysmshost say that you will receive code like, 202 for wrong mobile number, 301 for wrong authentication, i want to receive those error code please help.
this is my code.
//sending message
$authKey = "my_authentication_key";
$senderId = "sender";
$message = urlencode("Hello Its Working..");
$route = "1";
$campaign = 'Default';
//Prepare you post parameters
$postData = array(
'authkey' => $authKey,
'mobiles' => $number,
'message' => $message,
'sender' => $senderId,
'route' => $route,
'campaign' => $campaign
);
//API URL
$url="http://sms.mysmshost.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if(curl_errno($ch))
{
echo curl_error($ch)."-curl_error<br/>";
$chcode =curl_errno($ch);
echo $chcode;
echo '<br/>error:' . curl_strerror($chcode)."<br/>";
}
curl_close($ch);
echo $output;
Curl_errorno() is not executing, even if i print them without if condition they give no result.
Try this
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$server_output = curl_exec($ch);
curl_close($ch);
print_r($server_output);

Php curl json post returns error

I am trying a little script to create and update domain names using Digital Ocean api v2 here - https://developers.digitalocean.com/documentation/v2/#update-a-domain-record
For some reason the response from the server is that I am missing record type.
Here is my code:
$headers = array(
'Content-Type:application/json',
'Authorization: Bearer ' . file_get_contents('token.txt') );
$rawdata = array(
'type' => 'A',
'name' => 'sub',
'data' => '162.10.66.0',
'priority' => null,
'port' => null,
'weight' => null
);
$postdata = json_encode($rawdata);
$ch = curl_init(); // initiate curl
$url = "https://api.digitalocean.com/v2/domains/mydomain.org/records";
curl_setopt($ch, CURLOPTURL,$url);
curl_setopt($ch, CURLOPTPOST, true);
curl_setopt($ch, CURLOPTPOSTFIELDS, $postdata);
curl_setopt($ch, CURLOPTRETURNTRANSFER, true);
curl_setopt($ch, CURLOPTHTTPHEADER, $headers);
$output = curlexec ($ch); // execute
curl_close ($ch); // close curl handle
vardump($output); // show output
This is the error
string(81) "{"id":"unprocessable_entity","message":"Record type is not included in the list"}"
What am I missing here?
It's not a PHP error, it's an error return by the webservice you're calling. Check their documentation to see if you're sending the right stuff to them.

Categories