Offline upload photo to Facebook with photo from web server - php

I've searched around everywhere without luck and found lots of examples to upload a photo to facebook when the user is in a session (i.e. the user is physically sitting at the computer and accessing the web page). I've tried the samples, and they work.
I noticed this unanswered question from last year on the same issue
Stackoverflow Question
My current app lets the user authorise off-line updates and I store the access_token, user_id, etc. and I can succesfully post to a users wall when they are offline.
I'm really struggling getting something to work with posting a photo to the users wall. Reading the Facebook documentation, I'm thinking you can only upload photos using multipart/form-data!?!?
That wouldn't work if the user isn't at their computer. Can you upload photos that are stored on a directory on my server?
Here's my code so far. Remember, this doesn't use a facebook session as the access_code has already been granted and stored beforehand. As I mentioned, posting to a users wall already works with this approach.
$filename= "#/myphotodir/filename.jpg");
$url = "https://graph.facebook.com/".$uid."/photos"; //$uid is fb user id
$ch = curl_init($url);
$attachment = array('access_token' => $access_token,
'app_id' => $app_id,
'name' => "A photo from me...",
'fileUpload' => true,
'message' => "my message",
'image' => $filename,
);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result= curl_exec($ch);
curl_close ($ch);
Edit: $result comes back false... forgot to add that.
Any help would be appreciated.
Many thanks,
Dean

You should use the Facebook SDK. With the Facebook SDK, you can use:
$facebook->setFileUploadSupport( true );
$parameters = array(
'access_token' => 'ACCESS_TOKEN_HERE',
'message' => 'PHOTO_CAPTION',
'image' => '#' . realpath( '/path_to_file.jpg' ) // Notice the # sign
);
$facebook->api( '/user_id/photos', 'post', $parameters );
This will post the photo to their default album. If you replace user_id with an album_id you can post to a specific album.

Related

Get Instagram Feeds using username/user id

Earlier I had used
https://www.instagram.com/graphql/query/?query_id=17888483320059182&variables=$result
Now from this month as instagram has changed there api I am unable to get feeds.
Any suggestion will be helpfull
Follow my steps
first, you will need to register your application on the Instagram developer site and obtain your Client ID & Client Secret code, then you have to create access_token with Client ID & Client Secret
visit here : https://elfsight.com/blog/2016/05/how-to-get-instagram-access-token/ for creating Client ID, Client Secret & access_token
Then, add following code in your controller function
$access_token = 'xxxxxxxxxx.xxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // your access_token will be this format
$count_feed = 2; // how many feed want to load
$requestURL = 'https://api.instagram.com/v1/users/self/media/recent?access_token='.$access_token.'&count='.$count_feed;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $requestURL,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => 1
));
$json_response = curl_exec($ch);
curl_close($ch);
$insta_feeds = json_decode($json_response, true);
_e($insta_feeds); // $insta_feeds['data'] will return feed
You can get the feed by using the Instagram library. check out the library here : https://github.com/suhindra/CodeIgniter-Instagram-API

Getting Twitch clip data via Twitch API and php

I am trying to get data of certain Twitch clip, for example this one https://clips.twitch.tv/MushyJollyWalrusUWot
$videosApi = 'https://api.twitch.tv/kraken/clips/savjz/MushyJollyWalrusUWot';
$clientId = 'my client id';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array(
'Client-ID: ' . $clientId
),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $videosApi
));
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response, TRUE);
print_r($json);
I am getting an array with 404 error, but this code works fine with another Twitch api stuff, for example Twitch vod:
$videosApi = 'https://api.twitch.tv/kraken/videos/125820676';
//the rest is same
Like I have found with videos, clips are addressed by their name and nothing else, so I removed the username from your example.
I ended up using this URL https://api.twitch.tv/kraken/clips/MushyJollyWalrusUWot, which successfully returned a slightly large JSON blob containing the clip's information, and I have saved it at this URL: PasteBin - "SO Answer - Getting Twitch clip data via Twitch API and php"
I used to be able to query some base URL like https://api.twitch.tv/kraken/ in order to see a list of available resources that I could query from then on by successively adding to the path, but the /kraken and /kraken/ roots give user information, and /kraken/base does not seem to be a valid resource.
The API documentation for accessing this from the shell seems to be here: Twitch Developers - Twitch API Overview
By the way, I just used the shell, and may have had to provide both a Client ID and an OAuth token with user_read scope. I followed this guide for my reoccurring situation: GitHub - raine/twitch-cli - Setup.
It's not PHP, so I did not review your code in full detail, but some of these steps may help you along with your conceptual troubleshooting.
just add your key
parameters(optional):
limit=10
game=Overwatch
trending=true
//set header for pretty print
header('Content-Type: application/json');
$videosApi = 'https://api.twitch.tv/kraken/clips/top?limit=100&channel=ratirl';
$clientId = 'secret app id provided by twitch';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array(
//standard api requirement from twitch api headers
'Accept: application/vnd.twitchtv.v5+json',
'Client-ID: ' . $clientId
),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $videosApi
));
$response = curl_exec($ch);
curl_close($ch);
//decode the response
$json = json_decode($response, JSON_PRETTY_PRINT);
//print response
print_r($json);

php Browser-based Uploading video to youtube channel apiv3

I have an application that can upload video in my youtube account, but after upgrading to YouTube API v3, the situation is complicated.
it used this implementation https://developers.google.com/youtube/2.0/developers_guide_protocol_browser_based_uploading
Youtube authorization previously looked like this.
$postData = "Email=".urlencode(Config::$youtubeEmail)."&Passwd=".urlencode(Config::$youtubePassword)."&service=youtube&source=".urlencode(Config::$youtubeAppName);
$curl = curl_init("https://www.google.com/youtube/accounts/ClientLogin");
curl_setopt($curl,CURLOPT_HEADER,"Content-Type:application/x-www-form-urlencoded");
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$postData);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,1);
$response = curl_exec($curl);
curl_close($curl);
//print_r($response);exit();
list($this->auth,$this->youtubeUser) = explode("\n",$response);
list($this->authLabel,$this->authValue) = array_map("trim",explode("=",$this->auth));
list($this->youtubeUserlabel,$this->youtubeUserValue) = array_map("trim",explode("=",$this->youtubeUser));
I received auth token, that was used to make auth token to youtube account, and was possible to upload video via form
$youtubeVideoKeywords = ""; // This is the uploading video keywords.
$youtubeVideoCategory = $this->getVideoCategory(); // This is the uploading video category. There are only certain categories that are accepted. See below the method
$data = '<?xml version="1.0"?'.'>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<media:title type="plain">'.stripslashes($youtubeVideoTitle).'</media:title>
<media:description type="plain">'.stripslashes($youtubeVideDescription).'</media:description>
<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">'.$youtubeVideoCategory.'</media:category>
<media:keywords>'.$youtubeVideoKeywords.'</media:keywords>
</media:group>
<yt:accessControl action="list" permission="denied"/>
</entry>';
$headers = array(
'Authorization: Bearer ' . $this->authValue,
'GData-Version: 2',
'X-GData-Key: key=' . Config::$youtubeDevKey,
'Content-Type: application/atom+xml; charset=UTF-8'
);
$curl = curl_init("http://gdata.youtube.com/action/GetUploadToken");
curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_TIMEOUT,10);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
curl_setopt($curl,CURLOPT_REFERER,true);
curl_setopt($curl,CURLOPT_HEADER,0);
$response = simplexml_load_string(curl_exec($curl));
curl_close($curl);
return $response;
I didnt need any permission to upload video, user only used form where writed title, desc etc, pickedup video from computer and hit upload. Everything was fine, users could upload video to my youtube channel. useres ere satisfied, because there wasn´t additional login.
But now, when i make curl request to https://www.google.com/youtube/accounts/ClientLogin it says, that i need oauth2.0 auth service.
So i generated oauth2 secrets to my service, made changes to code, but when user want to use this application he need to be logged to google account and allow permissions to use web app.
New code snippet:
When user want to upload video, i check for auth code from oauth2service, and make curl for code, if doesnt exist
$url = 'https://accounts.google.com/o/oauth2/v2/auth?';
$url .= 'client_id=' . Config::$googleClientId;
$url .= '&redirect_uri=' . urlencode(Config::$googleRedirectUrl);
$url .= '&scope=' . urlencode("https://www.googleapis.com/auth/youtube");
$url .= '&response_type=code';
It returns me to redirect page, when i get a code, store it to application for later use. User write down info about video, and hit next button. I make new thread to upload service, use generated code to get a access token, which is used to form upload
$curl = curl_init('https://accounts.google.com/o/oauth2/token');
$post_fields = array(
'code' => $code,
'client_id' => Config::$googleClientId,
'client_secret' => Config::$googleSecretCode,
'redirect_uri' => Config::$googleRedirectUrl,
'grant_type' => 'authorization_code'
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_fields));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
//send request
$response = curl_exec($curl);
curl_close($curl);
$json = json_decode($response,true);
$this->authValue = $json["access_token"];
// The method returns response xml
$response = false;
$youtubeVideoKeywords = ""; // This is the uploading video keywords.
$youtubeVideoCategory = $this->getVideoCategory(); // This is the uploading video category. There are only certain categories that are accepted. See below the method
$data = '<?xml version="1.0"?'.'>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<media:title type="plain">'.stripslashes($youtubeVideoTitle).'</media:title>
<media:description type="plain">'.stripslashes($youtubeVideDescription).'</media:description>
<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">'.$youtubeVideoCategory.'</media:category>
<media:keywords>'.$youtubeVideoKeywords.'</media:keywords>
</media:group>
<yt:accessControl action="list" permission="denied"/>
</entry>';
$headers = array(
'Authorization: Bearer ' . $this->authValue,
'GData-Version: 2',
'X-GData-Key: key=' . Config::$youtubeDevKey,
'Content-Type: application/atom+xml; charset=UTF-8'
);
$curl = curl_init("http://gdata.youtube.com/action/GetUploadToken");
curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_TIMEOUT,10);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
curl_setopt($curl,CURLOPT_REFERER,true);
curl_setopt($curl,CURLOPT_HEADER,0);
$response = simplexml_load_string(curl_exec($curl));
curl_close($curl);
return $response;
Everything is fine, now i have got form, where action is to youtube server with token. everything work.
But now needs a user's consent to use web application, why? i have got my youtube account where videos are stored, no need information about user google account. Its very annoying, because user must be logged to application, after login it tells you, that must be logged to google account...
is there any workaround/solution that can make upload video to my youtube channel same easy as before without oauth2 please?
You need to setup with a service account which means assigning domain-wide delegations: https://console.developers.google.com/apis/credentials
"To support server-to-server interactions, first create a service account for your project in the API Console. If you want to access user data for users in your G Suite domain, then delegate domain-wide access to the service account.
Then, your application prepares to make authorized API calls by using the service account's credentials to request an access token from the OAuth 2.0 auth server.
Finally, your application can use the access token to call Google APIs."
Help: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
Without a service account it will always require a human user to accept a consent screen, whereas the service account bypasses the consent screen making it applicable for such operations where you wish for it to run in the background. It's not covered very well in their documentation (or I have yet to find a good resource... even though I feel like I've turned every stone on this planet).
I am having trouble getting tokens to work but have gotten service scripts working before... perhaps we can help one another? http://fb.com/jmt193 :)
I will reply to questions if you ask them.

PHP Upload Image from URL to Facebook [duplicate]

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_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);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

PHP - Upload a web hosted photo to facebook album via Graph API

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_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);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

Categories