Posting a Photo to Fousquare API V2 - php

I'm trying to post a photo to Foursquare API using the /photos/add method, and I'm having a little difficulites. I either get a 401 (missing file) or 502 (foursquare is down). Here is my code:
$ch = curl_init();
// file image name and it's located in the same folder
$image = "cupcakes.jpg";
// I've tried all of these and no luck
$s = array("file" => "#".$image, "photo" => "#".$image, "image" => "#".$image);
// I've also tried to send raw data:
//curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($image));
$url = "https://api.foursquare.com/v2/photos/add?oauth_token=TOKENHERE&checknId=4fecf6abe4b0369bc7389903";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $s);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// image/jpeg type
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: image/jpeg"));
$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// I get either 502 / 401 (Foursquare is down or File is missing)
echo $result;
Anyone have any idea what I'm doing wrong? The documentation for the endpoint is here: https://developer.foursquare.com/docs/photos/add -- in particular it implies that the photo data should be body of the POST request?

I've fixed the problem, turns out the param that you need to send to foursquare is "photo". All the other params must be included in the POST array as well.
Even though the content-type is requested as "image/jpeg", I've just put in "Except:" and it works fine. I'm not 100% sure why that goes through, but it does. Updated code below:
$s = array("photo" => "#".$image, "checkinId" => "4fecf6abe4b0369bc7389903");
$url = "https://api.foursquare.com/v2/photos/add?oauth_token=TOKENHERE&v=20120609";
.....
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
Everything else can stay the same. Happy posting!

Related

How to stop PHP cURL upload inserting "Boundary" into the "Content-Type" field?

I'm using the below code to upload an MP4 file to a web service, using PHP cURL.
I've specified the 'Content-Type' as 'video/mp4', in CURLOPT_HTTPHEADER.
Unfortunately, having uploaded the file, the 'Content-Type' stored for it in the service displays as: "content_type":"video/mp4; boundary=----WebKitFormBoundaryfjNZ5VkJS8z3CB9X"
As you can see, the 'boundary' has been inserted into the 'content_type'.
When I then download the file, it fails to play, with a 'file unsupported/file extension incorrect/file corrupt' message.
$authorization = "Authorization: Bearer [token]";
$args['file'] = curl_file_create('C:\example\example.mp4','video/mp4','example');
$url='[example web service URL]';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data', 'Accept: application/vnd.mendeley-content-ticket.1+json', $authorization));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS , $args);
$response = curl_exec($ch); // URL encoded output - needs to be URL encoded to get the HREF link header
curl_close($ch);
Would be extremely grateful for any help, advice or pointers!
Maybe the API doesn't expects a POST multipart, but the actual contents in the body itself:
Ref: How to POST a large amount of data within PHP curl without memory overhead?
You need to use PUT method for the actual contents of the file to go inside the body - if you use POST, it will try to send as a form.
$authorization = "Authorization: Bearer [token]";
$file = 'C:\example\example.mp4';
$infile = fopen($file, 'r');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.mendeley.com/file_contents");
curl_setopt($ch, CURLOPT_PUT, 1 ); // needed for file upload
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file));
curl_setopt($ch, CURLOPT_INFILE, $infile);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: video/mp4', 'Accept: application/vnd.mendeley-content-ticket.1+json', $authorization));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
I have the same problem calling a Openai API from PHP curl.
I send options: Content-Type and Authorization (with my api key) but, when I send request, I receive this error:
Invalid Content-Type header (application/json; boundary=------------------------66a0b850cd1421c8), expected application/json
I tried to use some of your options with no success.
I cannot remove the boundary parameter added automatically.

cURL PHP: uploading photo to Instagram

I authorized to Instagram, got all cookies, etc.
Now it's time to make request at https://www.instagram.com/create/upload/photo/.
In Chrome's inspector I see that browser sends these post data (where the binary photo is probably blob):
upload_id: 1539936226445
photo: (binary)
media_type: 1
And custom headers:
x-csrftoken: ACCESS_TOKEN_THAT_I_ALREADY_WROTE_INTO_THE_FILE
x-instagram-ajax: 723425780848
x-requested-with: XMLHttpRequest
But when I do the same request using cURL (passing posts and header that I wrote upper), I get 403 Forbidden, but should get 200 Ok with JSON response.
Here is how I make request:
$this->headers['csrftoken'] = $this->getFileData('csrftoken');
// generate upload_id for post field
$uploadId = number_format(round(microtime(true) * 1000), 0, '', '');
// generate binary from image file (maybe not correct)
$file_bin = fopen($file, 'rb');
// all my post fields
$params = array(
'upload_id' => $uploadId,
'photo' => $file_bin,
'media_type' => '1',
);
$ch = curl_init('https://www.instagram.com/create/upload/photo/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
// custom headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-csrftoken: '.$this->headers['csrftoken'],
'x-instagram-ajax: '.$this->headers['x-instagram-ajax'],
'x-requested-with: '.$this->headers['x-requested-with']
));
curl_setopt($ch, CURLOPT_POST, true);
// post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
// and finally get 403 forbidden instead of 200 ok with json response
$result = curl_exec($ch);
curl_close($ch);
return $result;
Does anybody know where the problem can hide?
Thanks so much for the help!
You should pass your cookies data, or start another session inside the code and send the cookie and the csrftoken of the session.

How to get magento API call response in browser

I gave up after 2 days. I want to get list of all products from magento2 api in browser. First I tried "http://mydomain.con/index.php/rest/V1/products?Authorization=Bearer_TOKENHERE?searchCriteria=" but it didn’t work (still not authenticated). The next thing I’ve tried was to call api with php curl:
<?php
//test for 1 product
//API URL for authentication
$apiURL="http://mydomain.con/index.php/rest/V1/integration/admin/token";
//parameters passing with URL
$data = array("username" => "test", "password" => "123456qwe");
$data_string = json_encode($data);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
$token = curl_exec($ch);
//decoding generated token and saving it in a variable
$token=json_decode($token);
//******************************************//
//Using above token into header
$headers = array("Authorization: Bearer ".$token);
//API URL to get all Magento 2 modules
$requestUrl='http://mydomain.con/index.php/rest/V1/products/24-MB01';
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//decoding result
$result=json_decode($result);
//printing result
print_r($requestUrl);
print_r($result);
?>
Unfortunately, this call get me a perfect answer in terminal in php storm (id, name, sku, price, etc in json) but if I want to get answer by browser it shows me Error 404 Request URL not found in server (when file is actually uploaded).
Sounds like a problem somewhere in web server. Check .htaccess in document root and host config in apache.

how to call an api via php and get a json file from it

I want to check all of the requested urls and if the url contains "video" folder in it, redirect it to an API file. then the API gives me a json files which only contains "respond:true" or "respond:false". In case of having respond:true in the json file the url must be showed and if the json file contains respond:false a predefined simple 403 page must be showed to the user.
I know that the fist part is possible with a simple code in .htaccess file like this:
RewriteRule ^your/special/folder/ /specified/url [R,L]
But I don't know how to do the second part. I mean how to get the result of API, which is in form of a json file and check it.
You can use CURL..
GET REQUEST
$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
POST REQUEST
$postdata = array(
'name' => 'Arfan'
);
$url = "https://example.com/api/user/create";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
You can also use file_get_content to get API data.
$json = file_get_contents("$url")
You can execute second part (Calling API and response): Call API using curl and process based on its response:
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, "api_url_here");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$api_response_json = curl_exec($ch);
curl_close($ch);
//convert json to PHP array for further process
$api_response_arr = json_decode($api_response_json);
if($api_response_arr['respond'] == true ){
//code for success here
}else{
// code for false here
}
Please note: Json response from API is depend on API Response, If API is giving response in json format ( can be based on params also ).

REST API Implementation Sample Code

I know nothing about implementing an API. I do know PHP a bit. I have a situation where I need to call a REST API method to purge cache on a CDN server. Can somebody help me with some sample code?
The following is the sample request:
PUT <<url>>
Authorization: TOK:12345-12345
Accept: application/json
Content-Type: application/json
Host: api.edgecast.com
Content-Length: 87
{
"MediaPath":"<<urlhere>>"
"MediaType":"3"
}
Can somebody help me with code to implement this rest api request?
Thanks in advance.
I had to find the hard way too. This has been tested (with slight modifications from my original code)
//## GoGrid PHP REST API Call
define('TOKEN','XXXXX-XXXXX-XXXXX-XXXXXX'); // found on the cdn admin My Settings
define('ACCOUNT_NUMBER','XXXX'); // found on the cdn admin Top Right corner
function purgeCacheFileFromCDN($urlToPurge) {
//## Build the request
$request_params = (object) array('MediaPath' => $urlToPurge, 'MediaType' => 8); // MediaType 8=small 3=large
$data = json_encode($request_params);
//## setup the connection and call.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.edgecast.com/v2/mcc/customers/'.ACCOUNT_NUMBER.'/edge/purge');
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1); // For debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); // no caching
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); // no caching
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: tok:'.TOKEN, 'Content-Type: application/json','Accept: application/json', 'Content-length: '.strlen($data)));
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch);
curl_close($ch);
//## check if error
if ($httpCode['http_code'] != 200) {
echo 'Error reported: '.print_r(array($head,$httpCode),1); // output it to stdout this will be emailed to me via cron capture.
}
}
Was too lazy to write from the scratch so copied from amazingly pink site that Google advises in the first page of results.
$data = array("a" => $a);
$ch = curl_init($this->_serviceUrl . $id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if(!$response) {
return false;
}
PS: The source search request: http://www.google.ru/search?q=php+sample+put+request+curl
Here is my source gist for my fully implemented Grunt task for anyone else thinking about working with the EdgeCast API. You'll find in my example that I use a node module to execute the curl command which purges the CDN.
This was that I ended up with after spending hours trying to get an HTTP request to work within Node. I was able to get one working in Ruby and Python, but did not meet the requirements of this project.

Categories