I'm trying to make a post request with php using curl however the json is not getting delivered to the REST API. Here is my code. In the webservice all I get is null value. I'm not sure where I'm going wrong.
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
Webservice code:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
Check PHP: curl_errno
There's probably a problem connecting to the server, and it's probably in one of your $header. To find out more, you need to show (in production, LOG it) the curl error.
In the future, please try to include a complete code sample, rather than just snippets
Code added from PHP: curl_strerror
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// #todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
Figured out a way to make this work.
Replaced $email_json_data = $this->post('email_json_data');
with $email_json_data = file_get_contents("php://input");
Related
I'm trying to call an API using PHP xml-rpc. Here is the API I'm trying to retreive : https://rtorrent-docs.readthedocs.io/en/latest/cmd-ref.html#term-d-multicall2
So far I made the following :
<?php
$username "test";
$password = "test";
function do_call($username, $password, $request) {
$url = "https://$username:$password#example.com:32491/RPC2";
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($request);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
return $data;
}
}
//$request = xmlrpc_encode_request("download_list", array()); //Give torrents hash
$request = xmlrpc_encode_request("d.multicall2", array("main", "d.name="));
$response = do_call($username, $password, $request);
var_dump($response);
Result :
string(310) " faultCode -501 faultString Unsupported target type found. "
Example call with xmlrpc :
rtxmlrpc --repr d.multicall2 '' tagged d.hash= d.name= d.custom=category
I don't understand why I'm getting this error
rTorrent version : 0.9.7/0.13.7
In issue 227 rakshasa says:
All commands are supposed to include a target as the first parameter,
in this case an empty string.
So you need to call like this see the first empty string: $request = xmlrpc_encode_request("d.multicall2", array("", "main", "d.name="));
I can't make it work.. :( I have this function (for create passthrough transcoder), when I run I see NULL in the web. If I test directly from the browser with the url, it does notify me that there is a problem an auth (apikey and acceskey)
function createPassthrough($name, $source_url, $recording = null)
{
$url = "https://sandbox.cloud.wowza.com/api/v1/transcoders";
$json = '{
"transcoder":{
"billing_mode":"pay_as_you_go",
"broadcast_location":"eu_belgium",
"delivery_method":"pull",
"name":"prueba",
"protocol":"rtsp",
"source_url":"url_camara",
"transcoder_Type":"passthrough",
"low_latency":true,
"buffer_size":0,
"play_maximum_connections":100,
"stream_smoother":false
}
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-Type: application/json; charset=utf-8',
'wsc-api-key:' . $apiKey,
'wsc-access-key:' . $accessKey,
));
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj);
}
What am I doing wrong? Thanks in advance.
You should check for curl errors after $result = curl_exec($ch);.
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
I'm having trouble trying to get my code running. I'm trying to use cUrl with a post and http authentication but I'm unable to get it to work.
I'm using the following code:
public function index(){
$call = $this->call("URL_TO_CALL", $this->getCredentials(), $this->getJson());
}
private function getCredentials(){
return "API_KEY_HERE";
}
private function getJson(){
return $json;
}
private function call($page, $credentials, $post){
$url = "URL_TO_CALL";
$page = "/shipments";
$headers = array(
"Content-type: application/vnd.shipment+json;charset=utf-8",
"Authorization: Basic :" . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the POST to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
}
The response I'm getting is:
{"errors":[{"code":3001}],"message":"Permission Denied. (insertShipment)"}
I was expecting a list of shipments. Am I doing something obviously wrong here?
Looking at your code, you stipulate the URL in a variable then stipulate the exact page, however when you set the URL for the curl, you are merely using the URL variable as opposed to URL + PAGE variables.
I'm trying to query data from another website by using PHP curl_setopt as below function, But I don't know to valid when my partner sever get any error as below description.
[Server Error 5xx]
500="Internal Server Error"
501="Not Implemented"
502="Bad Gateway"
503="Service Unavailable"
504="Gateway Timeout"
505="HTTP Version Not Supported"
public function getNumber() {
$url = "http://website/PalmHallServer_kl/!queryLuckNumberRecordByPeriods.action";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: Json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$contents = curl_exec($ch);
$res = false;
if ($contents) {
$res = TRUE;
} else {
$res = FALSE;
}
echo json_encode(array("res" => $res, 'data' => $contents));
}
First tell curl that you want to see the headers returned
curl_setopt($ch, CURLOPT_HEADER, true);
Then you can get Response code using
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
To see all the information contained in the response headers you can do
print_r(curl_getinfo($ch));
I'm trying to connect with hubstaff api, has anyone ever tried it? I'm a newbie in php-cURL, how do you convert this to PHP Curl?
curl -H "App-Token: BMyQnju-4tknuBQMsN0ujr6NWF5ohQaP9de8AWMJXik" -H "Auth-Token: X-vfv2c7jf_0NKoHLbX1t4yftK-TI-jZ4d7roNegw24" "http://api.hubstaff.com/v1/users"
It also would not show any result of I do this:
// Standard data
$data['app_token'] = $this->app_token;
// Debugging output
$this->debug = array();
$this->debug['HTTP Method'] = $http_method;
// Create a cURL handle
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'App-Token: ' . $this->app_token,
'Content-Type: application/xml'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Send data
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Debugging output
$this->debug['Posted Data'] = $data;
}
// Execute cURL request
$curl_response = curl_exec($ch);
// Save CURL debugging info
$this->debug['Last Response'] = $curl_response;
$this->debug['Curl Info'] = curl_getinfo($ch);
// Close cURL handle
curl_close($ch);
// Parse response
$response =$curl_response;// $this->parseAsciiResponse($curl_response);
// Return parsed response
return $response;
Im just trying to get my Auth-Token
Any help would be greatly appreciated.
#Michal I have solved my own problem and created this simple class to help anyone else in connecting with hubstaff fast. feel free for any suggestions and optimizations
class HubstaffApi {
private $app_token = '';
private $auth_token = '';
private $debug = [];
public function __construct($app_token, $auth_token) {
$this->app_token = $app_token;
$this->auth_token = $auth_token;
}
private function sendRequest($api_method, $http_method = 'GET', $data = null) {
// Standard data
$data['app_token'] = $this->app_token;
$request_url = "https://api.hubstaff.com/v1/";
// Debugging output
$this->debug = array();
$this->debug['Request URL'] = $request_url . $api_method;
// Create a cURL handle
$ch = curl_init();
// Set the request
curl_setopt($ch, CURLOPT_URL, $request_url . $api_method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'App-Token: ' . $this->app_token,
'Auth-Token: ' . $this->auth_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Send data
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Debugging output
$this->debug['Posted Data'] = $data;
}
// Execute cURL request
$curl_response = curl_exec($ch);
// Save CURL debugging info
$this->debug['Last Response'] = $curl_response;
$this->debug['Curl Info'] = curl_getinfo($ch);
// Close cURL handle
curl_close($ch);
// Parse response
$response = $curl_response;
// Return parsed response
return $response;
}
public function users(array $parameters = array()) {
return $this->sendRequest('users', 'GET', $parameters);
}
public function activities(array $parameters = array()) {
return $this->sendRequest('activities', 'GET', $parameters);
}
public function screenshots(array $parameters = array()) {
return $this->sendRequest('screenshots', 'GET', $parameters);
}
}
You can simply use this by:
$Hubstaff = new HubstaffApi(
YOUR_APP_TOKEN,
YOUR_AUTH_TOKEN); //simply get auth token in developer.hubstaff 's generator, it doesn't expire anyway.
$response = $Hubstaff->activities([
"start_time" => "2015-09-10T00:00:00+08:00:00",
"stop_time" => "2015-09-10T24:00:00+08:00:00",
"users" => YOUR_HUBSTAFF_ID
]);
echo $response;