How to convert this CURL command into PHP code - php

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.

Related

Shutter Stock API PHP Post Object formatting

I am talking to the Shutter Stock API. I am certain the problem is not SS but more the formatting of my PHP Curl post as if I send this request via terminal I get a proper response.
The Terminal curl comand is as follows:
curl "https://api.shutterstock.com/v2/images/licenses?subscription_id=$SUBSCRIPTION_ID" \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header "Content-Type: application/json" \
-X POST \
--data '{
"images": [
{ "image_id": "137111171" }
]
}
so I am playing with sending this as a PHP curl instead and here is what I have:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = new Object();
$params = {
'images' : {'image_id' : '137111171'}
};
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_decode($params));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
/*$json = json_decode($response, true);
if (json_last_error()) {
echo '<span style="font-weight:bold;color:red;">Error: ' . $response . '</span>';
} else {*/
return $response;
The response form Shutter Stock is "Decode body failure" which is a custom error response. I think the problem is in the $params variable and how it is formatted. Problem is that this is a post, I suspect that on the other side SS is decoding this in a specific way. The proper curl parameter is in the bash curl above as:
--data '{
"images": [
{ "image_id": "137111171" }
]
Does anyone have any suggestions about how to properly format this particular --data value so that I can send it as a POST?
Thanks
your PHP code contains invalid syntax, also PHP has no class named Object, but you're probably looking for StdObject, but even that doesn't make much sense here.. also you're not urlencoding $SUBSCRIPTION_ID . remove the invalid syntax parts, and use json_encode, not json_decode..
curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( array (
'images' => array (
array (
'image_id' => '137111171'
)
)
), JSON_OBJECT_AS_ARRAY ) );
(edit, going by the comments, the api requires applicable data to be an array instead of an object, thus i added the JSON_OBJECT_AS_ARRAY flag.)
I think you pass wrong CURLOPT_POSTFIELDS data. Try:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = [
'images' => ['image_id' => '137111171']
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;

Post the data with header in curl not working in php?

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

DropBox API application/octet-stream header

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&para2=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);

curl POST -F to php cUrl

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.

How to use PHP CURL function to do the same request?

Here is my curl commaad line .
curl -u 'username:password' -X GET -H 'Accept: application/json' -H 'Content-Type: application/xml' -d '<request><layout>1</layout><filtermode>category</filtermode><filtervalue>115399046</filtervalue><limit>1</limit><start></start><sortfield></sortfield><sortdir></sortdir></request>' https://example.com/contacts
I use curl command line. It works for me. Now, I need do it in PHP.
The hard part is: The server accept GET request, but need a xml string in request body. I have tried to change GET to POST, the server did NOT return the correct message.
<?php
$ch = curl_init();
$credentials = "user:pass";
$data = 'xml string';
$page = "/contacts";
$headers = array( "GET ".$page." HTTP/1.0", "Content-type: application/xml", "Accept: application/json", "Authorization: Basic " . base64_encode($credentials) );
curl_setopt($ch, CURLOPT_URL, 'example.com/contacts');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
?>
You can't put the GET line in $header, that causes an invalid header to be sent. The PHP equivalent of -X GET is:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

Categories