Uploading a picture to facebook - php

I am trying to upload a image to a gallery on a facebook fan page, here is my code thus far,
$ch = curl_init();
$data = array('type' => 'client_cred', 'client_id' => 'app_id','client_secret'=>'secret_key',' redirect_uri'=>'http://apps.facebook.com/my-application/'); // your connect url here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$rs = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
$data = explode("=",$rs);
$token = $data[1];
$album_id = '1234';
$file= 'http://my.website.com/my-application/sketch.jpg';
$data = array(basename($file) => "#".realpath($file),
//filename, where $row['file_location'] is a file hosted on my server
"caption" => "test",
"aid" => $album_id, //valid aid, as demonstrated above
"access_token" => $token
);
$ch2 = curl_init();
$url = "https://graph.facebook.com/".$album_id."/photos";
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_HEADER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch2, CURLOPT_POST, true);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
$op = curl_exec($ch2);
When I echo $token, I seem to be getting the token, but when I run the script, I get this error, {"error":{"type":"OAuthAccessTokenException","message":"An access token is required to request this resource."} , I have NO idea why it is doing this!
Basically what I am doing in that code is getting the access token with curl, and then, uploading the photo to my album also via curl, but I keep getting that error!
Any help would be appreciated, thank you!

Ok, got it working, here is the code, assuming that you have a valid session going.
$token = $session['access_token'];
//upload photo
$file= 'photo.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
This will upload the specified image to the session holders gallery, it will create a album if there is not one present, also you can access the token via the session array as demonstrated above.
Hope this helps someone out.

Probably your application doesn't have needed permissions.
To request permissions via OAuth, use
the scope argument in your
authorization request, and include a
comma separated list of all the
permissions you want to request.
http://developers.facebook.com/docs/authentication/permissions

Related

Set cookie using cURL

I’m building a login system in php where I need to use credentials from another website, I’m using an API to login to another server and I’m doing it using cURL. The server where the login credentials are stored does create a cookie with a unique tolken after the user has logged in correctly and this cookie is important to view other webpages and interrogate this pages using other APIs.
This is what I’ve done so far and it seems to work fine, in the login controller php file I’ve got this code
$km_username = filter_var($_POST['userName'], FILTER_SANITIZE_STRING);
$km_user_password = $_POST['userPassword'];
$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
$fh = fopen($cookieFile, "w");
fwrite($fh, "");
fclose($fh);
}
$url = 'https://www.apiwebsite.com/api/login.jsp?';
$fields = array(
'userid' => $km_username,
'password' => $km_user_password
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
$content = curl_exec($ch);
curl_close($ch);
In the page where I want to interrogate the server to get other datas I’ve got
$dates = array(
'd_inizio' => '01/01/2017',
'd_fine' => '31/12/2017'
);
$url = "https://www.apiwebsite.com/api/ricevute.jsp?";
$cookie = "../../km-controllers/cookies.txt";
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dates));
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
So basically after user has logged into the website cURL saves a cookie txt file into my server and this allows me to use that file any other time i want to make another call using for example a different api
Now the question is: what happen if I’ve got more than one user logging into the system? Do I need to create x number of cookies according on how many users log into the system? Would it not be simpler to save the cookie into the user’s browser?
Yes, you should use a different file for each client. What you can do is use tempnam() to generate a unique filename for the client, and save this in a session variable, then use it as the cookie jar. The login controller can do this:
session_start();
if (!isset($_SESSION['cookiefile'])) {
$cookiefile = tempnam(".", "cookie");
$_SESSION['cookiefile'] = basename($cookiefile);
}
And then the later page can use
$cookie = "../../km-controllers/" . $_SESSION['cookiefile'];
When the user logs out, you should delete this file and remove the session variable.
There's nothing that will automatically pass the cookies through from the curl session to the client browser or vice versa. If you don't want to save the cookies in a file, you can use curl_getinfo($ch, CURLINFO_COOKIELIST) to get the cookies, but you'll then have to parse the info yourself, and later use CURLOPT_COOKIE to set each cookie when making future calls. The cookie file automates all this.
Full code for login controller.
session_start(); // This needs to be at the very beginning of your script, before anything that produces output
//...
$km_username = filter_var($_POST['userName'], FILTER_SANITIZE_STRING);
$km_user_password = $_POST['userPassword'];
if (!isset($_SESSION['cookiefile'])) {
$cookieFile = tempnam(".", "cookie");
$_SESSION['cookiefile'] = basename($cookiefile);
file_put_contents($cookieFile, "");
}
$cookieFile = $_SESSION['cookiefile'];
$url = 'https://www.apiwebsite.com/api/login.jsp?';
$fields = array(
'userid' => $km_username,
'password' => $km_user_password
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
$content = curl_exec($ch);
curl_close($ch);
And the later interrogator:
session_start(); // at very beginning
// ...
$dates = array(
'd_inizio' => '01/01/2017',
'd_fine' => '31/12/2017'
);
$url = "https://www.apiwebsite.com/api/ricevute.jsp?";
if (!isset($_SESSION['cookiefile'])) {
die("no cookie file");
}
$cookie = "../../km-controllers/" . $_SESSION['cookiefile'];
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dates));
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

Bing Image search API v5.0 example for PHP

I'm trying, without success, to get some results using Bing's Image search API without HTTP/Request2.php component (as used in the official examples).
I understand that the only two required parameters to make a very primitive call are q which is the query string and the subscription key. The key must be sent using headers. After looking around I found this very simple example to send headers with PHP:
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$aHTTP = array(
'Ocp-Apim-Subscription-Key' => 'xxxxxxx',
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
But it does not output anything. Would you kindly help me with a very basic example of use of Bing's API?
SOLVED
Thanks to Vadim's hint I changed the way headers are sent and now output is a Json encoded result. (Remember to add your API subscription key.)
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: xxxxx'
));
$content = curl_exec($ch);
echo $content;
Just another tip. The syntax of query filters and other parameters change form version to version. For example the following work correctly in version 5.0:
To search only for JPEG images of cats and get 30 results use:
q=cats&encodingFormat='jpeg'&count=30
To search only for 'portrait' aspect images with size between 200x200 and 500x500 use:
q=cats&aspect=Tall&size=Medium
Try using cURL
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$key = "xxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
Here is my working code..
Replace ******** with your bing subscription key.
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: *******************'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
foreach ($myContents->value as $imageContent) {
echo '<pre/>';
print_r($imageContent);
}
}

Error when doing cURL request

This code always returns user doesn't exist from the API:
$data2 = array('user'=>$vars['mcusername'],
'pwd'=>$vars['mcpassword'],
'group'=>$postfields['group'],
'action'=>'Save');
// Connect to dvb API
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?part=userconfig&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
$data = curl_exec($ch);
curl_close($ch);
The string that works in a browser is this:
dvbapi.html?part=userconfig&user=PeterTest&pwd=obfuscated&group=1,2&disabled=0&action=Save
When you access the URL in the browser, you're performing a GET. In your cURL attempt, you're attempting to POST. This is likely the issue; the script may only accept GET.
Try using this cURL code instead:
// Gather up all the values to send to the script
$data2 = array('part' => 'userconfig',
'user' => $vars['mcusername'],
'pwd' => $vars['mcpassword'],
'group' => $postfields['group'],
'action' => 'Save');
// Generate the request URL
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?".http_build_query($data2);
// cURL the URL for a responce
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
// Show the responce
var_dump($data);
You can use http_build_query() to turn your array into a URL-encoded string to make the GET request.

Instagram POST "like" in PHP isn't working any more?

Today I tried to post a like via PHP (Curl) without luck. The output is that a token is required but I used a working token. I tried the same token with JS and it works.
Did Instagram changed some things bout PHP?
Here is my code:
<?php
$media_id = '615839918291043487_528338984';
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes?";
$access_token_parameters = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba',
'action' => 'like'
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_GET,true);
curl_setopt($curl,CURLOPT_GETFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
?>
Output.:
{"meta":{"error_type":"OAuthParameterException","code":400,"error_message":"Missing client_id or access_token URL parameter."}}
I tried it on several server, with several proxies, several client and token. Hopefully you know what's going on.
To add a like to a photo you need to do it via POST. The following is an modified version of your code to do this.
<?php
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes";
$fields = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>

Post a feed on facebook after a form on my website

I have a news form on my website. After creating this news message I want to publish it on Facebook. I tried alot of things, but nothing was working. Here is my class:
<?php
class Facebook {
const FACEBOOK_APP_ID = 'MY_APP_ID';
const FACEBOOK_APP_SECRET = 'MY_APP_SECRET';
const FACEBOOK_ACCESS_TOKEN_URI = 'https://graph.facebook.com/oauth/access_token';
const FACEBOOK_FEED_URI = 'https://graph.facebook.com/app/feed';
private function getAccessToken() {
$params = array(
'client_id' => self::FACEBOOK_APP_ID,
'client_secret' => self::FACEBOOK_APP_SECRET,
'grant_type' => 'client_credentials',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_ACCESS_TOKEN_URI);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);
curl_close($ch);
return substr($data, strpos($data, '=') + 1);
}
public function sendFeed() {
$params = array(
'access_token' => $this->getAccessToken(),
'message' => $message,
'name' => $name,
'link' => $url,
'description' => $description,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_FEED_URI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close ($ch);
return $data;
}
}
If I call the method sendFeed() it returns the following:
{"id":"404322099626551_404397542952340"}
I think the submit was successfull, but when I visit my page on facebook, there is no new feed. What am I doing wrong? I searched the complete day and couldn't get it to work. I thank you for your help.
What you are doing here is posting it on your user's feed. You are using a user access token. What you want to use is a page access token.
You'll need the manage_pages permission to perform tasks on behalf of your page.
In addition you should consider using the official PHP SDK, it'll make accessing Facebook's API much easier and improve readability.

Categories