I'm trying to upload a config file via PHP's CURL to the Cisco APIC-EM via POST but am receiving an unexpected error:
//File Upload
echo "<b>File Upload:</b><br>";
$namespace = "config";
$data = array(
"version" => "",
"response" =>
array(
"nameSpace" => $namespace,
"encrypted" => false,
"id" => "",
"md5Checksum" => "",
"sha1Checksum" => "",
"fileFormat" => "",
"fileSize" => "",
"downloadPath" => "http://hama0942.global.bdfgroup.net/network/net_config/bdfbrsao00000000rt02.txt",
"name" => "bdfbrsao00000000rt02.txt",
"attributeInfo" => "object"
)
);
$data = json_encode($data);
//For Debugging only - Request
echo "<br>Request:<br>";
echo '<pre>';
print_r($data);
echo '</pre>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, "https://hams1484.global.bdfgroup.net/api/v1/file/".$namespace);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form- data", "X-Auth-Token: ".$serviceTicket));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array($data));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ch);
echo "<br><b>Request-Header: </b>".curl_getinfo($ch, CURLINFO_HEADER_OUT )."<br><br>";
//For Output Debugging only - Response
echo "<br>Response:<br>";
echo '<pre>';
print_r(json_decode($response));
echo '</pre>';
curl_close($ch);
echo "<br><hr>";
This is the result:
File Upload:
Request:
{"version":"","response":{"nameSpace":"config","encrypted":false,"id":"","md5Checksum":"","sha1Checksum":"","fileFormat":"","fileSize":"","downloadPath":"http:\/\/hama0942.global.bdfgroup.net\/network\/net_config\/bdfbrsao00000000rt02.txt","name":"bdfbrsao00000000rt02.txt","attributeInfo":"object"}}
Request-Header: POST /api/v1/file/config HTTP/1.1 Host: hams1484.global.bdfgroup.net Accept: */* X-Auth-Token: ST-1111-OUiNBLtgALg2ufcwFrh5-cas Content-Length: 436 Expect: 100-continue Content-Type: multipart/form-data; boundary=------------------------5e86cb7113449960
Response:
stdClass Object
(
[response] => stdClass Object
(
[errorCode] => 7062
[message] => Unexpected error
[detail] => Non valid file object
)
[version] => 1.0
)
I'm afraid that there is something wrong with the CURL settings but I'm not sure. Has someone an idea what is wrong here? I'm using PHP7.
Thanks.
I have been struggling with this for a long time now and finally found a solution for this.
1 : File for upload has to be local file on the server your are CURL'ing from.
2 : $file = realpath("filenameOnServer");
3 : $config = new CURLfile($file);
4 : $array = array("fileUpload" => $config); $array = json_encode($array);
5 : curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: multipart/form-data; charset=utf-8;',
'X-Auth-Token: ' . $token,
));
6 : send the array as POST variable in the CURL. Nothing else is needed
Related
I am having trouble finding out why my script is returning "result":null,"error" rather than a successful transaction.
This curl command works when run manually;
curl --user username:password --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "sendtoaddress", "params": ["someaddress", 0.001] }' -H 'content-type: text/plain;' http://".199.42.160.41:8332
Here is the code I'm using attempting to replicate the above curl command which works;
$url = "http://199.42.160.41:8332";
$address = "address";
$address = '"'.$address.'"'; //Adding double quotation marks around the address.
$amount = 0.001;
$bounty = $address.', '.$amount;
$payload = ["jsonrpc" => "1.0", "id" => "curltest", "method" => "sendtoaddress", "params" => [$bounty] ];
$payload=json_encode($payload);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res=curl_exec($ch);
echo "<br/><br/>";
echo "Result from attempting to send transaction is below this line</br>";
print_r($res);
curl_close($ch);
With the above I can see that $payload is set as follows;
$payload is set to the following;
Array ( [jsonrpc] => 1.0 [id] => curltest [method] => sendtoaddress [params] => Array ( [0] => "sendtoaddress", 0.001 ) )
What am I missing or doing wrong?
Edit: My $payload looks like this once it's been converted to jsonrpc
{"jsonrpc":"1.0","id":"curltest","method":"sendtoaddress","params":["someaddress, 0.001"]}
From what I can tell, I need to have it look like this;
{"jsonrpc":"1.0","id":"curltest","method":"sendtoaddress","params":["someaddress", 0.001]}
Found and fixed the issue. $payload wasn't what I needed, I needed to use two variables for it to be formatted correctly for jsonrpc.
//$payload = ["jsonrpc" => "1.0", "id" => "curltest", "method" => "sendtoaddress", "params" => [$bounty] ];
$payload = ["jsonrpc" => "1.0", "id" => "curltest", "method" => "sendtoaddress", "params" => [$address, $amount] ];
Now that $payload is set correctly the script works!
I'm sending a request to a JSON API system (http://help.solarwinds.com/backup/documentation/Content/service-management/json-api/login.htm) using PHP:
$base = 'https://cloudbackup.management/jsonapi';
$vars = array(
"jsonrpc" => "2.0",
"method" => "Login",
"params" => array(
"partner" => "partner",
"username" => "username",
"password" => "pass",
),
"id" => "1",
);
$ch = curl_init( $base );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$output = json_decode($response, true);
But its returning this array in $output
Array
(
[error] => Array
(
[code] => -32700
[data] => 119
[message] => Parse error: Failed to parse request body: * Line 1, Column 1
'--------------------------' is not a number.
)
[id] => jsonrpc
[jsonrpc] => 2.0
)
I cannot work out why it's returning an error, because I'm sending the correct parameters that it says in the docs.
Can someone point me in the right direction or if I have missed something?
Set the content-type to application/json as curl is likely defaulting to sending it as x-www-form-urlencoded
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
also JSON-encode your array:
$jsonDataEncoded = json_encode($vars);
Full refactored sample:
$base = 'https://cloudbackup.management/jsonapi';
$vars = array(
"jsonrpc" => "2.0",
"method" => "Login",
"params" => array(
"partner" => "partner",
"username" => "username",
"password" => "pass",
),
"id" => "1",
);
$jsonDataEncoded = json_encode($jsonData);
$ch = curl_init( $base );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$output = json_decode($response, true);
How to update user profile picture in Quickblox using php codeigntier ?
Documentation found at
http://quickblox.com/developers/Users
after found rest api i have found the solution for how to upload profile picture to quickblox user.
there are three 3 steps for uploading content as per quickblox rest api
First you generate token from the quickblox and then perform these 3 steps
Create file
https://quickblox.com/developers/Content#Create_a_file
$strFilename = '2.jpeg';
$post_body = http_build_query(array(
'blob[content_type]' => 'image/jpeg',
'blob[name]' =>$strFilename,
));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, QB_API_ENDPOINT.'blobs.json');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
'QuickBlox-REST-API-Version: 0.1.0',
'QB-Token: ' . $token
));
$response = curl_exec($curl);
$error = curl_error($curl);
if ($response) {
return $response;
} else {
return false;
}
curl_close($curl);
After this curl call you have got the response and in response got the response like this
[blob] => Array
(
[id] => 7178102
[uid] => f9cc9d7938c4468f8bdccdcb68fb5d8c00
[content_type] => image/jpeg
[name] => 2.jpeg
[size] =>
[created_at] => 2017-02-07T10:35:38Z
[updated_at] => 2017-02-07T10:35:38Z
[ref_count] => 1
[blob_status] =>
[set_completed_at] =>
[public] => 1
[last_read_access_ts] =>
[lifetime] => 8600
[account_id] => 56721
[app_id] =>
[blob_object_access] => Array
(
[id] => 7178102
[blob_id] => 7178102
[expires] => 2017-02-07T11:35:38Z
[object_access_type] => Write
[params] => https://qbprod.s3.amazonaws.com/?Content-Type=image%2Fjpeg&Expires=Tue%2C%2007%20Feb%202017%2011%3A35%3A38%20GMT&acl=public-read&key=f9cc9d7938c4468f8bdccdcb68fb5d8c00&policy=eyJleHBpcmF0aW9uIjoiMjAxNy0wMi0wN1QxMTozNTozOFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJxYnByb2QifSx7ImFjbCI6InB1YmxpYy1yZWFkIn0seyJDb250ZW50LVR5cGUiOiJpbWFnZS9qcGVnIn0seyJzdWNjZXNzX2FjdGlvbl9zdGF0dXMiOiIyMDEifSx7IkV4cGlyZXMiOiJUdWUsIDA3IEZlYiAyMDE3IDExOjM1OjM4IEdNVCJ9LHsia2V5IjoiZjljYzlkNzkzOGM0NDY4ZjhiZGNjZGNiNjhmYjVkOGMwMCJ9LHsieC1hbXotY3JlZGVudGlhbCI6IkFLSUFJWTdLRk0yM1hHWEo3UjdBLzIwMTcwMjA3L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDE3MDIwN1QxMDM1MzhaIn1dfQ%3D%3D&success_action_status=201&x-amz-algorithm=AWS4-HMAC-SHA256&x-amz-credential=AKIAIY7KFM23XGXJ7R7A%2F20170207%2Fus-east-1%2Fs3%2Faws4_request&x-amz-date=20170207T103538Z&x-amz-signature=5e236c3da60a922951c8ab6281ae82af3a88e37c15d8630ad6ff590610a87fd8
)
)
Upload file
so you have to used the params url parameters and make another call for uploading file
$strFilename = '2.jpeg';
$url = 'https://qbprod.s3.amazonaws.com/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'Content-Type' => $arr['Content-Type'],
'Expires'=>$arr['Expires'],
'acl'=>$arr['acl'],
'key'=>$arr['key'],
'policy'=>$arr['policy'],
'success_action_status'=>$arr['success_action_status'],
'x-amz-algorithm'=>$arr['x-amz-algorithm'],
'x-amz-credential'=>$arr['x-amz-credential'],
'x-amz-date'=>$arr['x-amz-date'],
'x-amz-signature'=>$arr['x-amz-signature'],
'file' => new CurlFile('2.jpeg', $arr['Content-Type'], $strFilename)
));
$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 204) {
echo 'Success!';
} else {
$error = substr($response, strpos($response, '<Code>') + 6);
echo substr($error, 0, strpos($error, '</Code>'));
}
return $response;
so by using this code your content file will be uploaded and you got the location of the file and used as profile picture or etc .
Declare file
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.quickblox.com/blobs/" . $strId . "/complete.xml"); // strId is blod id return by 1 step
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "blob[size]=10000"); //your file size
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$headers = array();
$headers[] = "Quickblox-Rest-Api-Version: 0.1.0";
$headers[] = "Qb-Token: " . $token;
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
return $result;
Please let me know the any issue regards the same.
Thanks
I am trying to authenticate to third party ticketing system, connect and retrieve agent info. I then want to parse retrieved file so as to only show specific info such as 'id' and' 'active_since', but I get an NULL error in browser. Any help?
FILE RETURNED BY THIRDPARTY
[agent] => Array
(
[active_since] => 2015-11-30T08:09:26-01:00
[available] => 1
[created_at] => 2015-05-14T19:15:18+00:00
[id] => XXXXX
[occasional] =>
[points] => 5520
[scoreboard_level_id] => 5000402007
[signature] =>
[signature_html] =>
Below is the PHP CURL code.
<?php
$username = "xxxxxxx";
$password = "xxxxxxx";
$url = 'http://support.xxxx.com/agents/xxx132067';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'header' => "Authorization: Basic " . base64_encode("$username:$password")
)
);
$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
$array["active_since"];
?>
Remove the 'header' => from the Authorization header. And it should be as below:
"Authorization: Basic " . base64_encode("$username:$password")
And I didn't see you are calling curl at all. Replace your file_get_contents with proper curl call.
$result = curl_exec($cURL);
curl_close($cURL);
I have the pages below.
Page json.php:
$json_data = array(
'first_name' => 'John',
'last_name' => 'Doe',
'birthdate' => '12/02/1977',
'files' => array(
array(
'name' => 'file1.zip',
'status' => 'good'
),
array(
'name' => 'file2.zip',
'status' => 'good'
)
)
);
$url = 'http://localhost/test.php';
$content = json_encode($json_data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
"Content-type: application/json",
"Content-Length: " . strlen($content)
)
);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content));
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT);
curl_close($curl);
echo $header_sent;
echo '<br>';
echo $status;
echo '<br>';
echo $json_response;
Page test.php:
echo '<pre>';
print_r($_POST);
echo '</pre>';
When I’m calling json.php from the browser, I get the following result:
POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150
200
Array
(
)
Why can’t I see the POST string I’m trying to send?
Edit:
If I don’t set the Content-type: application/json header (as per #landons’s comment), I get the following result:
POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded
200
Array
(
[json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name":
)
PHP does not use it's internal request parsing for POST requests if the content type is not set to one of the two official content types that are used when posting forms from inside a browser. (e.g. the only allowed content types are multipart/form-data, often used for file uploads, and the default value application/x-www-form-urlencoded).
If you want to use a different content-type, you are on your own, e.g. you have to do all the parsing yourself when fetching the request body from php://input.
In fact, your content type is currently wrong. It is NOT application/json, because the data reads json={...}, which is incorrect when being parsed as json.