I have problems to upload a photo to an album by the facebook API. this is my code.
$facebook->setFileUploadSupport(true);
//Create an album
$album_details = array(
'message'=> 'Message',
'name'=> 'Album Name'
);
$create_album = $facebook->api('/me/albums?access_token='.$access_token, 'post', $album_details);
//Get album ID of the album you've just created
$album_id = $create_album['id'];
echo $album_id." - ";
//Upload a photo to album of ID...
$photo_details = array();
$img = "app.jpg";
$photo_details['source'] = '#' . $img;
$photo_details['message'] = 'Wow.. cool image!';
$upload_photo = $facebook->api('/'.$album_id.'/photos?access_token='.$access_token, 'post', $photo_details);
When i upload the image with a form, it works! but this code does not upload the image into the album.
I have tried also with CURL but there is nothing... i don't know where the problem is...
After testing few things on Graph API Explorer, Here's a working PHP Version:
<?php
# Path to facebook's PHP SDK.
require_once("facebook.php");
# Facebook application config.
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'fileUpload' => true # Optional and can be set later as well (Using setFileUploadSupport() method).
);
# Create a new facebook object.
$facebook = new Facebook($config);
# Current user ID.
$user_id = $facebook->getUser();
# Check to see if we have user ID.
if($user_id) {
# If we have a user ID, it probably means we have a logged in user.
# If not, we'll get an exception, which we handle below.
try {
# Get the current user access token:
$access_token = $facebook->getAccessToken();
# Create an album:
$album_details = array(
'access_token' => $access_token,
'name' => 'Album Name',
'message' => 'Your album message goes here',
);
$create_album = $facebook->api('/me/albums', 'POST', $album_details);
# Get album ID of the album you've just created:
$album_id = $create_album['id'];
# Output album ID:
echo 'Album ID: ' . $album_id;
# Upload photo to the album we've created above:
$image_absolute_url = 'http://domain.com/image.jpg';
$photo_details = array();
$photo_details['access_token'] = $access_token;
$photo_details['url'] = $image_absolute_url; # Use this to upload image using an Absolute URL.
$photo_details['message'] = 'Your picture message/caption goes here';
//$image_relative_url = 'my_image.jpg';
//$photo_details['source'] = '#' . realpath($image_relative_url); # Use this to upload image from using a Relative URL. (Currently commented out).
$upload_photo = $facebook->api('/' . $album_id . '/photos', 'POST', $photo_details);
# Output photo ID:
echo '<br>Photo ID: ' . $upload_photo['id'];
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array('scope' => 'publish_stream, user_photos'));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
# No user, print a link for the user to login and give the required permissions to perform tasks.
$params = array(
'scope' => 'publish_stream, user_photos', # These permissions are required in order to upload image to user's profile.
);
$login_url = $facebook->getLoginUrl($params);
echo 'Please login.';
}
?>
I have added comments so you could understand what it does by reading the code.
This works with both absolute url and relative url, I have commented out code for uploading image using relative url as you have mentioned in your comments you can't read real path of the image.
EDIT: Note: The user has to give extended permissions to your facebook application to upload images to their profile, Those permissions are publish_stream and user_photos.
Let me know if this helped you and if it works :)
$user = $this->facebook->getUser();
$this->facebook->setFileUploadSupport(true);
$user_profile = $this->facebook->api('/me');
$album_details = array(
'message' => 'Hello everybody this is me ' . $user_profile['name'],
'name' => 'I am so slim because I dont have money to eat....:('
);
$create_album = $this->facebook->api('/me/albums', 'post', $album_details);
// Upload a picture
$photo_details = array(
'message' => 'I am so slim because I dont have money to eat....:('
);
$photo_details['image'] = '#' . realpath('./a.jpg');
$upload_photo = $this->facebook->api('/' . $create_album['id'] . '/photos', 'post', $photo_details);
Please use $facebook on $this->facebook
Related
so I have a little problem, when first time user use my app It is redirected to:
http://www.facebook.com/MY_APP.../?state=f5c913239670dc934fae1274a81fa538&code=AQAmY5k8gRRt7woNKmpc_6z2eHgT-2B3prjNEDYFma1KqpQDKob-CS_bWfqd0qPkQD-tGoVdKUK8twGZRnLhoiotpZ3SlBeo3uusfmMyWDYStv-D79RvQEP8m9M8S8GYlbN3x1eLEd4D3RajWokTNAhRP8a1VB9VSKAb35xXFzg3PkheRKHqjr-nex5jcjM7Nv2B_JEV1w8AzM2LJg2M9kAb#_=_
And I get error: page not found
Durring permission approvig my link is: https://www.facebook.com/dialog/oauth?client_id=456080124457246&redirect_uri=http%3A%2F%2Fpadekime.wu.lt%2Fplaukai%2Findex.php&state=2c46a86dae43af0467da756bc3e52779&scope=publish_stream%2Cphoto_upload
I added redirect link and now It go to:
http://www.padekime.wu.lt/plaukai/kontekstas/?state=5abfd521df3c68ae55f26ad51a704743&code=AQDMmpZC-_Yxatq4xuAE60Tl2qW4pXCvDeghrbMGGu3Lg1X8zqrk-lvxRc3VOoYvgoLvATJhcsyykZnPoM7XI2sXih-nJhKrjx-HS3GFapELmC4KvX4KyN-VU-znHopkA-q_zcuIffJ0tY79CXPn7mo05BpxfvPntXaUAe7ymLf1p8Kg29eERaP5nw1dChbwwZ13FNY7BXD2ymAsFHPNH5zw#_=_
Possible to make that after permission approved go normally to my app http://www.facebook.com/Padekime/app_456080124457246 without /?state=..... ?
My code now looks like:
<?php
require_once('images/Facebook.php');
$facebook = new Facebook(array(
'appId' => '456080124457246',
'secret' => 'e2956a6e1de8791363faedb1ef44c408',
));
# Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$redirectUri = 'http://www.padekime.wu.lt/plaukai/kontekstas/';
# Photo Caption
$photoCaption = 'Patarimų plaukams sužinojau čia http://goo.gl/otwhf';
# Absolute Path to your image.
$imageUrl = 'http://padekime.wu.lt/plaukai/images/PlaukaiNeuzvedus.jpg'; // Example URL
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'url' => $imageUrl,
'redirect_uri' => $redirectUri
);
$apiResponse = $facebook->api('/me/photos', 'POST', $post_data);
} catch (FacebookApiException $e) {
$user = null;
error_log($e);
}
} else {
$redirectUri = 'http://www.padekime.wu.lt/plaukai/kontekstas/';
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload',
'redirect_uri' => $redirectUri
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
As I understand problem is somewhere here, but I cant solve it.
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
So if you know something about this, please help me, thank you very much.
SOLUTION:
I added ?ref=ts to $redirectUri:
$redirectUri = 'http://www.facebook.com/Padekime/app_456080124457246?ref=ts';
SOLUTION:
I added ?ref=ts to $redirectUri:
$redirectUri = 'http://www.facebook.com/Padekime/app_456080124457246?ref=ts';
i am trying to post to my friends' feeds using this code, but it is not working . i am stuck, any help ??
$app_url ="http://localhost.local/PMS/facebook/PostWithPHP.php";
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APPSECRET',
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
$user_friends = $facebook->api('/me/friends');
sort($user_friends['data']);
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
$vars = array(
'message' => 'My Message',
'name' => 'title',
'caption' => 'Caption',
'link' => 'Link',
'description' => 'Description',
'picture' => 'image'
);
foreach($user_friends['data'] as $f){
$sendTo = $f['id'];
$sendToName = $f['name'];
$result = $facebook->api("/".$sendTo ."/feed", 'post', $vars);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
echo "<script type='text/javascript'>";
echo "top.location.href = '{$loginUrl}';";
echo "</script>";
}
and another question is that using this code, but with replacing $facebook->api("/".$sendTo ."/feed", 'post', $vars); by $facebook->api("/me/feed", 'post', $vars); and of course without looping friends, posts on my timeline. how can i make it post on my wall ??
I guess for a post to a timeline you will need an accessToken from the user where to publish the content. In your case you just have the accessToken of the registered user, not of his friends. That is a restriction by FB I think.
1st check you getting the user id(place echo and check) if not try this... I think this will help you brother
$token_url = "https://graph.facebook.com/oauth/access_token?" ."client_id=" . $app_id ."&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$access_token = file_get_contents($token_url);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$user_id = $data["user_id"];
There are a few things wrong with your code. First of all, make sure the link and picture parameters for the post are valid URLs. Facebook will give you a error message otherwise ((#100) link URL is not properly formatted). Also, the link must go to the Canvas or Site URL for your application.
That should solve the issues with posting to a friend's wall.
However, may I remind you that your application is in violation of the Facebook Platform Policy. Facebook doesn't allow multiple posts to the stream (whether its yours or a friends) unless there is explicit permission from the user. It also to stop common friends seeing the same message from multiple friends.
You can follow the tutorial here:
https://www.webniraj.com/2012/11/22/facebook-api-posting-a-status-update/
But, instead of making a API call to: /me/feed, you replace me with the friend's User ID, so it looks like /12345/feed
Please note that Facebook has now disabled posting to Friends' walls via the API. Instead, you should either tag the user in an action or use the Requests API.
I've photos on my web server,now,i've to upload it to fan page photo album.Is there any limit for photo upload.After uploading it to fan page photo album,i've to post it to wall.
// Get the page access token
$accounts = $facebook->api('/my_account_id/accounts', 'GET', $params);
$data = $accounts['data'];
foreach($data as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage )
$fanpage_token = $account['access_token'];
}
// Get all albums from the page
// Must use app access token, not page token!
// You can also use a static album id to test
$fanpage_albums = $facebook->api($fanpage . '/albums', 'GET', $params);
$albums = $fanpage_albums['data'];
$sorted = array();
foreach($albums as $album) {
if( ! strpos($album['name'], 'Special') )
continue;
$sorted[] = $album;
}
$album_id = $sorted[0]['id']; // Get the first one. Shouldn't be empty!
// Upload the photo (previously uploaded by user)
$args = array(
'message' => 'Von ' . $teilnehmer_name,
'image' => '#' . realpath($path. $_FILES['media']['name']),
'aid' => $album_id,
'no_story' => 1 // Nicht auf der Wall anzeigen (Thank God for that),
'access_token' => $fanpage_token // note, we use the page token here
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
if( is_array( $photo ) && ! empty( $photo['id'] ) )
echo 'Photo uploaded. Check it on Graph API Explorer. ID: ' . $photo['id'];
I tried the above code but it is not working.
Do not use realpath(), use the folder name/file name, it will work then you need a page access token.
Like this app http://www.facebook.com/pages/Welcher-Simpsons-Charackter-bist-du/143753942375692?sk=app_197801216980659
help me ...
sample code for you
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('src/facebook.php');
$config=array();
$config['appid']='****';
$config['secret']='*********';
$config['appurl']='http://apps.facebook.com/YOUR APP/';
$configsdk = array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'fileUpload' => TRUE, // optional
);
$facebook = new Facebook($configsdk);
$user_id = $facebook->getUser();
if(empty($user_id)){
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $GLOBALS['config']['appid'] . "&redirect_uri=" . urlencode($config['appurl']).'&scope=publish_stream';
echo ("<script> top.location.href='".$dialog_url ."' </script>");
break;
}
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user=$facebook->api('me','GET');
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
$src['0']='http://techsinter.com/apps/picbackg.jpg';
$iTmp2 = imagecreatefromjpeg($src['0']);
$iOut = imagecreatetruecolor ("740","680") ;
#imagecopy ($iOut,$iTmp2,0,0,0,0,imagesx($iTmp2),imagesy($iTmp2));
#imagedestroy ($iTmp2);
$white = imagecolorallocate($iOut, 0xFF, 0xFF, 0xFF);
// Path to our ttf font file
$font_file = './arial.ttf';
// Draw the text 'PHP Manual' using font size 13
$photo=time().'.png';
imagefttext($iOut, 13, 0, 300, 40, $white, $font_file, $user['name']);
imagepng($iOut,$photo);
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'source' => '#' . $photo,
'message' => 'Hello',
)
);
unlink($photo);
?>
well that app is getting users permission to publish & after getting this permissions uploading a photo from a page is exactly like uploading a photo from an app
at first you must get user's name from api merge user's name & a photo
upload it to users profile Read here :
Upload a photo to a User's profile
https://developers.facebook.com/docs/reference/php/facebook-api/
I have developed an application for facebook. I want that whenever any user add my application by clicking on allow permission dialog, a message is automatically posted on the users wall only for the first time.
<?php
include_once 'fb_sdk_212/src/facebook.php';
include_once 'config.php';
$flag_post=0;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
'cookie' => true,
'domain' => 'xxxxx.in'
));
$session = $facebook->getSession();
if (!$session) {
$flag_post=1;
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,user_birthday,status_update,publish_stream'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$updated = date("l, F j, Y", strtotime($me['updated_time']));
echo "Hello " . $me['name'] . "<br />";
echo "You last updated your profile on " . $updated."<br/>";
if($flag_post == 1){
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
echo $can_post;
$attachment = array(
'name' => 'Tracer',
'description' => 'xxxx',
'caption' => 'xxxxx',
'picture' => 'images/mt75.jpg',
'link' => 'tracer/'
);
if($can_post){
# post it!
$facebook->api('/'.$uid.'/feed', 'post', $attachment );
echo 'posted';
} else {
die('Permissions required!');
}
}
} catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}
}
?>
Well you need to get publish_stream extended permission.
http://developers.facebook.com/docs/authentication/permissions
This can be done in the permission dialog
http://developers.facebook.com/docs/reference/javascript/FB.login
by adding publish_stream to the perms list.
After that you will be able to publish to the user's wall at any time.
I would do one of the following:
Add a field in a database table to indicate that it has been done. Then just check if it has been set. If cookies are enabled on the users PC you could use but using a database would be best.
Get the user to take an action to do the post. So it requires a user action. This has the disadvantage that some users may not do it.
I feel like you can handle this fairly easily without Facebook being involved in decision to publish to the users wall or not. In your database's user table you should have a column for first_fb_post. When a user account is created it should default to 0, then once you publish the wall post it should be updated to 1.
And your facebook publish function would be set like:
if($first_fb_post == 0)
{
//your FB publishing code here
//update your user table to mark this users first_fb_post to 1
}
You could hook into the first time the user "installs" your app. When they do this they are redirected to your site with a get parameter of 'code' set in the url:
if(isset($_GET['code'])){
// User Authorized app. Lets hook the install event.
if($can_post){
# post it!
$facebook->api('/'.$uid.'/feed', 'post', $attachment );
echo 'posted';
} else {
die('Permissions required!');
}
}