POST Request PHP with Curl - php

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>';
}

Related

How to prevent wp_remote_post to add backslashes

To publish a plugin I must change my code to use the Wordpress HTTP Api.
Therefore, I have translate my code.
Before.
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$ch = curl_init($url);
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)
));
$result = curl_exec($ch);
After
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$result = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json'),
'body' => wp_json_encode($data_string),
'method' => 'POST',
'timeout' => 60, // added
'redirection' => 5, // added
'blocking' => true, // added
'httpversion' => '1.0',
'sslverify' => false,
));
But with the function wp_remote_post I have this problem.
When JSON data is sended to remote host, the data has the backslashes inside.
Example:
{\"Param1\":\"ValueParam1\","Param2\":\"ValueParam2\"}
What is wrong?
Have I wrong something in translate the origin code?
I need some help to send JSON data without these escaping characters.
Thanks.
Pass JSON_HEX_QUOT as a second parameter to wp_json_encode to escape the double quotes without a slash. See: https://developer.wordpress.org/reference/functions/wp_json_encode/ and https://www.php.net/manual/en/json.constants.php for more details.

PHP curl POST for Watson Video Enrichment

Am trying to use PHP 7.2 to submit a new job to the Watson Video Enrichment API.
Here's my code:
//set some vars for all tasks
$apiUrl = 'https://api-dal.watsonmedia.ibm.com/video-enrichment/v2';
$apiKey = 'xxxxxxxx';
//vars for this task
$path = '/jobs';
$name = 'Test1';
$notification_url = 'https://example.com/notification.php';
$url = 'https://example.com/video.mp4';
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => "simple.custom-model",
"upload" => array(
"url" => $url
)
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL, $apiUrl.$path );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: APIKey '.$apiKey
));
$result = curl_exec($ch);
echo $result;
But I can't get it to work, even with varying CURLOPTs, like:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
I keep getting the response: Bad Request.
Here's the API docs.
Am I setting up the POST CURL all wrong? Is my $data array wrong? Any idea how to fix this?
Reading their API documentation, it looks like the field preset is not of type string. Rather it has a schema defined here. This appears similar to how you are using the upload schema.
You should change your data array to look like this:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"video_url" => "https://example.com/path/to/your/video"
),
"upload" => array(
"url" => $url
)
);
Ok, I figured it out. Thanks to #TheGentleman for pointing the way.
My data array should look like:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"simple.custom-model" => array(
"video_url" => $url,
"language" => "en-US"
)
),
"upload" => array(
"url" => $url
)
);

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);

Trouble with POST API using cURL

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);

How to get a list of users of bugzilla project using XMLRPC after login

I'm looking for XMLRPC keywords to find out a list of users of a BUGZILLA project.
Here is my code, login works fine and im' able to use several keywords to find out what i need : Bug.search, Bug.fields.
public function loginBz($url,$login,$password,$getResult)
{
set_time_limit(0);
$URI = $url;
$xml_data = array(
'login' => $login,
'password' => $password,
'remember' => 1
);
$ch = curl_init();
$file_cookie = tempnam ("/tmp", "CURLCOOKIE");
$options = array(
//CURLOPT_VERBOSE => true,
CURLOPT_URL => $URI,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: text/xml', 'charset=utf-8' )
);
curl_setopt($ch, CURLOPT_TIMEOUT,60);
curl_setopt_array($ch, $options);
$request = xmlrpc_encode_request("User.login", $xml_data);
// var_dump($request);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file_cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
//print_r ($response);
if($getResult)
return $response;
else
return $ch;
}
public function getFieldsBz($product,$component,$ch){
$xml_data = array(
'product' => $product,
'component' => '$component'
);
$request = xmlrpc_encode_request("Bug.user", $xml_data); // create a request for filing bugs
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
return $response;
}
I've been searching into BugZilla API but did not found what I need : List of Users for a product Bz.
Does anyone know which keyword I have to use in xmlrpc_encode_request(keyword,array_filter) ?
It would help :)
First there isn't a method called Bug.user, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/Bug.html for a complete list.
There is a method called User.get, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/User.html#get
There is a parameter called groups which may do what you want depending on how you setup Bugzilla security.
You can use https://xmlrpc.devzing.com/ to experiment or if you upgrade to Bugzilla 5.x you can use the new REST API. https://www.bugzilla.org/docs/5.0/en/html/api/Bugzilla/WebService/Server/REST.html

Categories