I'm attempting to POST a local file to an API, it works if I use command line curl but not when I try using php cURL. I set up some variables for the headers and body
$headers = array();
$headers[] = 'Authorization: Passcode '.$passcode;
$headers[] = 'FileType: STD';
$api_url = 'https://url.com';
$field_json = json_encode($field).';type=application/json'
$filepath = realpath('path/file.csv');
$file = new CURLFile($filepath,'text/csv');
curl based on the API's specifications works if I set it as a string and use exec
$cmd = "curl -X POST -H \"$headers[0]\" -H \"$headers[1]\" -F \"field=$field_json\" -F \"filename=#$filepath\" $api_url";
exec($cmd,$result); //This works successfully
but when I attempt to send the POST using the following code with PHP cURL, I get a vague error response 'Unexpected error'
$body = array(
'field' => $field_json,
'filename' => $file
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//curl_setopt($ch, CURLOPT_SAFE_UPLOAD, FALSE);
$result = curl_exec($ch);
curl_close($ch);
echo json_encode($result);
I'm using PHP 5.5.9 and have tried it using the old way with # and the filepath.
Related
When I run the curl command below, I receive success response and the image can upload as normal:
curl -X POST -F file=#/myFolder/pic.png -H "Authorization: Bearer {tokenX}" https://api.cloudflare.com/client/v4/accounts/{accountX}/images/v1
But when I use PHP to exec curl by the code below:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/accounts/{accountX}/images/v1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'file' => '#' .realpath('/myFolder/pic.png'));
$headers = array();
$headers[] = 'Authorization: Bearer {tokenX}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Cloudflare return an error: ERROR 9422: Decode error: image failed to be decoded: Uploaded image must have image/jpeg or image/png content type
I run curl command and PHP code on the same local server.
What did I do wrong?
echo json_decode(shell_exec('curl -X POST -F file=#./Rectangle36.png -H "Authorization: Bearer {{token}}" https://api.cloudflare.com/client/v4/accounts/{{account}}/images/v1'))->result->variants[0];
I want use php curl to interact with coinbase api. Simple API calls that does not require data to be passed are successful. What I want to do is create address.
CLI curl works. The command line curl command sample is below:
curl https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' \
-d '{"name": "New receive address"}'
}
My php code excerpt
$apiurl = "https://api.coinbase.com";
$secret = "coinbase api secret";
$method = "POST";
$requestPath = "/v2/accounts/actualAccountID/addresses";
$body = "";
$url = $apiurl.$requestPath;
$data["name"] = "curl smj6 ary";
$body=json_encode($data);
$string = $timestamp.$method.$requestPath.$body;
$sig = hash_hmac('sha256', $string, $secret);
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if($method == "POST"){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$headers = [
"CB-ACCESS-KEY: xxx",
"CB-ACCESS-SIGN:$sig",
"CB-ACCESS-TIMESTAMP: $timestamp",
"CB-VERSION: 2018-03-21",
"accept: application/json;charset=utf-8"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
It returns
{"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Since it works with listing user. I guess th error occurs the way iam passing post data to curl.
Similar Questions that I found on SO but none solves my issue. Please help!
Invalid Signature Coinbase
CoinBase "invalid signature" PHP Buy API Request
How to declare CURL body for CoinBase API call
Api key authentication for coinbase
UPDATE:
$apiurl = "https://api.coinbase.com/v2/";
$requestPath = "accounts/$accountid/addresses";
returns same error
There are sites that convert the command line cURL syntax to PHP, like https://incarnate.github.io/curl-to-php/
I just pasted your command and:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
$headers[] = "CB-ACCESS-KEY: <your api key>";
$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal
curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST
Same thing I have tried with php But it is giving the following error
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}
The following one I have tried
$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'name'=>'NEW USER',
'is_platform_access_only'=>'true',
));
//Adding Header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$developer_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.
I have rise the same question in Perl tag with Perl code. There I got answer by user #melpomene.
We should encode the data as JSON. It is working,
Then the final code is
$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);
I'm trying to run a CURL command in my PHP file, but I'm not able to see the output. The following is modified slightly without the real usernames/passwords/URLs.
The reason I'm trying to see the output is to make sure the CURL command is working as expected (I've run it in bash so I know the expected result).
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0');
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: text/plain;charset=utf-8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, '$username:$password');
curl_setopt($ch, CURLOPT_POSTFIELDS, '$data');
// grab URL and pass it to the browser
curl_exec($ch);
I've run the following to make sure CURL is installed with my PHP server, and that is the case:
function _is_curl_installed() {
if (in_array ('curl', get_loaded_extensions())) {
return true;
}
else {
return false;
}
}
// Ouput text to user based on test
if (_is_curl_installed()) {
echo "cURL is <span style=\"color:blue\">installed</span> on this server";
} else {
echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";
}
Is there something I'm doing wrong? I've run the curl command on my bash, and I'm able to see a response fine:
curl -X POST --user $username:$password --header "Content-Type: text/plain;charset=utf-8" --header "Accept: application/json" --data-binary #Test.txt "http://www.example.com"
Try this example:
<?php
// SEND CURL POST DATA
$jsonData = array(
'user' => 'Username',
'pass' => 'Password'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//API Url
$url = 'http://fxstar.eu/JSON/api.php';
//Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(Content-Type: text/plain;charset=utf-8);
//Execute the request
echo $result = curl_exec($ch);
?>
Get json from js:
<?php
// GET JSON CONTENT FROM JS api.php
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
$json = json_decode($jsonStr);
?>
Currently im working on box platform, and trying to upload a file to the box server. Box uses cURL to upload files, and i'm trying to send cURl requests from php. So far i've converted most of the cURL commads to php jargon, but i could't figure out how to pass in the attributes(name, path, containing folder) of the file to be uploaded.
here is the cURL
curl https://upload.box.com/api/2.0/files/content -H "Authorization: Bearer APP_USER_TOKEN" -X POST -F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=#Jon_Snow.jpeg
and here is the php version for the incomplete cURL command.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://upload.box.com/api/2.0/files/content");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Authorization: Bearer ".json_decode($accessToken, true )['access_token'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
How do i do the last part of the cURL command which is
-F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=#Jon_Snow.jpeg
Edit: the suggestion of 'possible duplicate' is not accurate, i am asking of a way to add attributes to the uploaded files in the form -F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' i dont see how the suggested answer is relevant
Found the answer, i needed to json_encode the attributes array and then use new \CURLFile() function to create a file handle, it did NOT work with realpath()
$attributes = array('name'=>$fileName,'parent'=>array('id'=>$folderId));
$file = new \CURLFile($filePath);
$fields = array('attributes' => json_encode($attributes), 'file' => $file);
$headers = array("Authorization: Bearer ".$accessToken);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
Try this: art about sending files via post and curlib
-F option means you're sending a post Field with name and content. Content in this case is from File becasue you're using # prefix