I'm attempting to make a cUrl request with PHP to the Dropbox API, in order to begin to upload a very large zip file. Here is the documentation I'm trying to implement, found at https://www.dropbox.com/developers/documentation/http/documentation#files-upload -
URL structure: https://content.dropboxapi.com/2/files/upload_session/start
Example cUrl Request:
curl -X POST https://content.dropboxapi.com/2/files/upload_session/start \
--header "Authorization: Bearer <get access token>" \
--header "Dropbox-API-Arg: {\"close\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #local_file.txt
And here is my code:
$uploads = wp_upload_dir();
$file = $uploads['basedir']."/maintainme/backups/files/backup_".$filename.'/'.$filename.'.zip';
$ch = curl_init();
$url = 'https://content.dropboxapi.com/2/files/upload_session/start';
$headers = array(
'Authorization: Bearer ' .$dropbox_token,
'Dropbox-API-Arg: {\"close\": false}',
'Content-Type: application/octet-stream',
);
$fields = array('file' => '#' . $file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields );
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$result = curl_exec($ch);
curl_close($ch);
The error message I get is:
Error in call to API function "files/upload_session/start": Bad HTTP "Content-Type" header: "application/octet-stream; boundary=------------------------1ee7d00b0e9b0c47". Expecting one of "application/octet-stream", "text/plain; charset=dropbox-cors-hack".
It seems that this 'Boundary=------------blahblahblah' gets appended to my content-type header each time I try to make this request. Anyone have any ideas??? Thanks!
Solved it! On a whim, I checked into the 'CURLOPT_POSTFIELDS' option found at http://php.net/manual/en/function.curl-setopt.php, and here's what it said:
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix. As of PHP 5.5.0, the # prefix is deprecated and files can be sent using CURLFile. The # prefix can be disabled for safe passing of values beginning with # by setting the CURLOPT_SAFE_UPLOAD option to TRUE.
The relevant part is bolded in the paragraph above. Apparently passing an array to the CURLOPT_POSTFIELDS option is what was appending that 'Boundary=----blahblahblah' the Content-Type and causing the API call to fail. I changed
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields );
to
curl_setopt($ch, CURLOPT_POSTFIELDS, '#'.$file );
and tried again. The initial issue was fixed, but I then encountered a new issue with the 'Dropbox-API-Arg' line in this section of code:
$headers = array(
'Authorization: Bearer ' .$dropbox_token,
'Dropbox-API-Arg: {\"close\": false}',
'Content-Type: application/octet-stream',
);
Turns out, these arguments need to be properly JSON-Encoded. I did this with the code below:
$args = array('close'=>false);
$args = json_encode($args);
and then changed
'Dropbox-API-Arg: {\"close\": false}'
to:
'Dropbox-API-Arg:'.$args
Here is the complete, final code:
$uploads = wp_upload_dir();
$file = $uploads['basedir']."/maintainme/backups/files/backup_".$filename.'/'.$filename.'.zip';
error_log($file);
$args = array('close'=>false);
$args = json_encode($args);
$ch = curl_init();
$url = 'https://content.dropboxapi.com/2/files/upload_session/start';
$headers = array(
'Authorization: Bearer ' .$dropbox_token,
'Dropbox-API-Arg:'.$args,
'Content-Type: application/octet-stream',
);
$fields = array('file' => '#' . $file);
error_log($fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, '#'.$file );
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$result = curl_exec($ch);
error_log($result);
curl_close($ch);
Related
$headers = array();
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
var_dump($result);
curl_close($curl);
I have the code above, i want to post to an api. Somehow its not working. I tried using a var_dump on the result variable. The result is:
string(117) "{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}"
Any idea why its not posting to the api?
The value of the $post=
{"AmountDebit":10,"Currency":"EUR","Invoice":"testinvoice 123","Services":{"ServiceList":[{"Action":"Pay","Name":"ideal","Parameters":[{"Name":"issuer","Value":"ABNANL2A"}]}]}}
Headers:
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
If you don't specify a Content-Type header when making a POST call with Curl, it will add one in with the value application/x-www-form-urlencoded.
From the Everything Curl book:
POSTing with curl's -d option will make it include a default header that looks like Content-Type: application/x-www-form-urlencoded. That's what your typical browser will use for a plain POST.
Many receivers of POST data don't care about or check the Content-Type header.
If that header is not good enough for you, you should, of course, replace that and instead provide the correct one.
Judging by your request, I imagine you'll need to add the following to the top of your script:
$headers[] = 'Content-Type: application/json';
But depending on the exact API you're posting to, this might need to be different.
Have You installed curl before using it.
If it not install try google for Curl installation
and use my curl function for post request its 100% working-
public function curlPostJson() {
$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' .strlen(json_encode($paramdata));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paramdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
$server_output = curl_exec($ch);
curl_close($ch);
return json_decode($server_output);
}
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);
Here is my code for trying to delete a file a file via the api
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/<MY-ZONE-ID>/purge_cache");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = [
'X-Auth-Email: MYEMAIL',
'X-Auth-Key: MY-AUTH-KEY',
'Content-Type: application/json'
];
$data = json_encode(array("files" => "https://example.com/file/".$filename));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
The response i get is as follows
{
"success":false,
"errors":[
{
"code":1012,
"message":"Request must contain one of \"purge_everything\" or \"files\", or \"tags"
}
],
"messages":[
],
"result":null
}
Documentation says tag is optional so it should work
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
-H "X-Auth-Email: user#example.com" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"files":["http://www.example.com/css/styles.css"],"tags":["some-tag","another-tag"]}'
What am In doing wrong here ?
I maybe because your files property is not an array.
Try
$data = json_encode(array("files" => array("https://example.com/file/".$filename)));
This is a bit confusing. Post Data is usually sent in key value pairs.
Also when the post data is an array curl changes the content type to multipart/form-data
When post data is sent as a query string, it's in the format of key1=value1&key2=value2
It appears the json is the value with no key.
I would try it both as an array and string and look at the request header.
In the request header look at the content-type and the data.
To get the request header in the curl return add this option:
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
You may need to add:
curl_setopt($ch, CURLOPT_POST, true);
$data[] = json_encode(array('files'=>"https://example.com/file/$filename"));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$data = json_encode(array('files'=>"https://example.com/file/$filename"));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
PS: You do not need to use the . concatenation when using double quotes for $filename
I am trying to translate this CURL command that is needed to communicate to a web-service.
curl -X POST -H 'Content-Type: application/gpx+xml' -H 'Accept: application/json' --data-binary #/home/x/gpslog.gpx "http://test.roadmatching.com/rest/mapmatch/?app_id=YOUR_APPID&app_key=YOUR_APPKEY" -o output.json
I have my own APPID and APPKEY that I substitute them in the command and also in php code. My gpx logs (xml files) are in /home/x folder that I want to send them to web-service.
I wrote this code but it seems doesn't work (in $params I've set some arguments that needed for me.):
$url = 'http://test.roadmatching.com/rest/mapmatch/';
$header = array('Content-Type: multipart/form-data');
$filePath= '/home/x/gpslog.gpx';
$fields = array('file' => new CurlFile($filePath));
$params = array('app_id' => 'MY-APP-ID', 'app_key' => 'MY-APP-KEY', 'output.groupByWays' => 'false', 'output.linkGeometries' => 'false','output.osmProjection' => 'false','output.linkMatchingError' => 'false','output.waypoints' => 'true','output.waypointsIds' => 'true');
$url .= '?' . http_build_query($params);
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($resource, CURLOPT_POST, 1);
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);
$result = json_decode(curl_exec($resource));
curl_close($resource);
I think the problem may arise because of "Content-Type: application/gpx+xml" that I don't know how to write it in php and also other options of the main CURL command.
After executing this piece of code the result is empty and no errors or warnings are produced.
I am using below post method for google account using curl but it gives me invalid_request error.
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=CENSORED&
redirect_uri=http://localhost/oauth2callback&
grant_type=authorization_code
Here is my PHP code with curl
$text ='test';
$URL = "https://accounts.google.com/o/oauth2/token";
$header = array(
"POST /o/oauth2/token HTTP/1.1",
"Host: accounts.google.com",
"Content-type: application/atom+xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"code=[my_code]&client_id=[my_client_id]&client_secret=[my_client_secret]& redirect_uri=http://localhost/curl_resp.php&grant_type=authorization_code",
"Content-length: ".strlen($text),
);
$xml_do = curl_init();
curl_setopt($xml_do, CURLOPT_URL, $URL);
curl_setopt($xml_do, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($xml_do, CURLOPT_TIMEOUT, 10);
curl_setopt($xml_do, CURLOPT_RETURNTRANSFER, true);
curl_setopt($xml_do, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($xml_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($xml_do, CURLOPT_POST, false);
curl_setopt($xml_do, CURLOPT_POSTFIELDS, $text);
curl_setopt($xml_do, CURLOPT_HTTPHEADER, $header);
And I am having invalid request error
I don't know anything about using Google's oAuth API, but from the examples that I have looked at so far, it looks like you are supposed to pass the values (i.e. code, client_id, etc.) in the post fields, not directly in the HTTP header.
The following example still doesn't work completely, but instead of getting a invalid_request error, it gives you invalid_grant. I think there is something else wrong in addition to what I've mentioned (perhaps you need new credentials from Google or something), but this might get you one step closer, at least:
$post = array(
"grant_type" => "authorization_code",
"code" => "your_code",
"client_id" => "your_client_id",
"client_secret" => "your_client_secret",
"redirect_uri" => "http://localhost/curl_resp.php"
);
$postText = http_build_query($post);
$url = "https://accounts.google.com/o/oauth2/token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postText);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
var_dump($result); // gets an error, "invalid_grant"
The response to your request actually includes a very readable description of the problem:
POST requests require a Content-length header.
Why do you have CURLOPT_POST set to false?
curl_setopt($xml_do, CURLOPT_POST, false);
Although some configurations of cURL will automatically change this to tru if CURLOPT_POSTFIELDS is set, you do not have a valid postfield.
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix.
It should either be in param=value syntax or an array passed.
I have used post array in CURL method and valid Google code and it worked for me
I was also having the same problem, where google returns an "invalid_xxx".
After much researching and troubleshooting, the problem lies with the encoding of the form itself! Do not use function 'http_builder_query', as it messses up the string and google cannot 'recognise' it. Example :
http_builder_query Output : "code=4%252FYYUT71KJ6..."
compared to
just a normal string : "code=4/YYUT71KJ6..."
Here is my working code, where i have placed 'x' in the locations that needs your own data (taken and modified from google oauth authentication)
$code_from_user_login = "4/YYUT71KJ6....";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$post_params = "code=" . $code_from_user_login . "&";
$post_params .= "redirect_uri=http://www.x.com/&";
$post_params .= "client_id=x.apps.googleusercontent.com&";
$post_params .= "client_secret=x&";
$post_params .= "grant_type=authorization_code&";
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
$result = curl_exec($ch);
print($result);
The result will be like :
'{
"access_token" : "ya29.AHES6ZSwJSHpTZ1t....",
"token_type" : "Bearer",
"expires_in" : 3599,
"id_token" : "eyJhbGciOiJSUzI1NiIsImtpZCI6IjU0MDQxOTZlMmQzOGNjYTA2MW...."
}'
Once you have the 'access_token', access the profile data with this url :
https://www.googleapis.com/oauth2/v1/userinfo?access_token=YOUR_ACCESS_TOKEN_HERE
~ end ~