I'm creating a FaceBook app where the user selects multiple images and the application generates a single image from them (PHP). I'm giving the generated image a semi-random name - $storage_url = $rack_directory . "rack_" . mt_rand() . mt_rand() . ".png"; (e.g. rack_2128639756968968165.png) and storing it temporarily as well.
I'd like the user to be able to upload the generated image to their Facebook profile directly from the page rather than downloading and then uploading it.
In looking over answers in this site as well as others it looks like I can use this:
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$post_login_url = "YOUR_POST-LOGIN_URL";
$album_name = 'YOUR_ALBUM_NAME';
$album_description = 'YOUR_ALBUM_DESCRIPTION';
$code = $_REQUEST["code"];
//Obtain the access_token with publish_stream permission
if(empty($code))
{
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url .
"'</script>");
}
else {
$token_url= "https://graph.facebook.com/oauth/"
. "access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
// Create a new album
$graph_url = "https://graph.facebook.com/me/albums?"
. "access_token=". $access_token;
$postdata = http_build_query(
array(
'name' => $album_name,
'message' => $album_description
)
);
$opts = array('http' =>
array(
'method'=> 'POST',
'header'=>
'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($graph_url, false,
$context));
// Get the new album ID
$album_id = $result->id;
//Show photo upload form and post to the Graph URL
$graph_url = "https://graph.facebook.com/". $album_id
. "/photos?access_token=" . $access_token;
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.$graph_url. ' "method="POST">';
echo 'Adding photo to album: ' . $album_name .'<br/><br/>';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message" type="text"
value=""><br/><br/>';
echo '<input type="submit" value="Upload" /><br/>';
echo '</form>';
echo '</body></html>';
}
...to generate a unique album and upload the picture...
But - I don't want to display a form that has a user browse to and upload (after they right/control click and save the image from the page). Just take the existing generated image displayed on the page and submit that.
Is there a function that I could use so that this process occurs and the only form requirement is to submit and upload?
Thanks.
What you need is the Facebook SDK :https://developers.facebook.com/docs/reference/php/
This makes all those "Graph" calls much simpler.
Pasting from that page:
// Load the facebook SDK
require_once("facebook.php");
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
try {
$uid = $facebook->getUser();
catch (FacebookApiException $e) {
// Not logged on - you should log them on. Various methods, but redirect to $facebook->getLoginURL() is simplest. Docs: https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
}
Once the user is logged on, you can upload also through the SDK:
// Now upload the file
try {
$facebook->setFileUploadSupport('http://MyDomain.com/');
$response = $facebook->api(
'/me/photos/',
'post',
array(
'message' => 'Image Cpation',
'source' => '#/path/to/image' // #-sign must be the first character
)
);
}
catch (FacebookApiException $e) {
error_log('Could not post image to Facebook.');
}
You cna use an album ID in place of "me" for uploading directly to a specific album. But working your way through the SDK will help a lot more than trying it all manually with the graph calls!
Sorry, It's not a complete "here's the code" answer (there's still a bit of work to go), but that should help you upload without prompting the user.
Related
i'm trying to upload video on Facebook page using this code. I have added all the compulsory credentials to add video. but when i select video and click upload button it json request says you dont have permission to upload video. I tried to debug this problem but couldn't succeed. please help me out. thank you
<?php
$app_id = "xxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "http://xxxxxxxx/test.php";
$video_title = "test_video_for_app";
$video_desc = "test_description";
$page_id = "xxxxxxxxxxxxxxxx"; // Set this to your APP_ID for Applications
$code = $_REQUEST["code"];
echo '<html><body>';
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url). "&scope=publish_actions,manage_pages";
echo('<script>top.location.href="' . $dialog_url . '";</script>');
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?". "title=" . $video_title. "&description=" . $video_desc. "&access_token=". $access_token;
// Create a simple form
echo '<form enctype="multipart/form-data" action=" '.$post_url.' "
method="POST">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" />';
echo '</form>';
}
echo '</body></html>';
?>
this is the responce coming from facebook
{
"error": {
"message": "(#100) No permission to publish the video",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "H1uOf8K83lL"
}
}
so finally after a long research i got the solution. we just need to add permission from developers.facebook.com.
fisrt go to developers.facebook.com
go to tools and support and select graph api explorer
then select your application and click on get access token
add the permission publish_action in that and click ok
u will get access token.
copy thataccess token and paste in place of
$access_token = file_get_contents($token_url);
it will be like
$access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
then run your code and its done
Let me first thank you for allowing me to ask some question here. I hope you can help me with the following question.
I want to post some message on User's Facebook status. It is successful with the following code:
$params = array('access_token'=>$access_token, 'message'=>$message);
$url = "https://graph.facebook.com/".$fbuserid."/feed";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
What do I need to add or do to post image and/or link affiliate to this post msg? Thank you!
In order to publish a photo to a user's album, you must have the publish_stream permission. With that grantedd, you can upload a photo by issuing an HTTP POST request with the photo content and an optional description to one these to Graph API connections:
https://graph.facebook.com/USER_ID/photos - The photo will be published to an album created for your app. We automatically create an album for your app if it does not already exist. All photos uploaded this way will then be added to this same album.
https://graph.facebook.com/ALBUM_ID/photos - The photo will be published to a specific, existing photo album, represented by the ALBUM_ID.
Example:
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$post_login_url = "YOUR_POST_LOGIN_URL";
$code = $_REQUEST["code"];
//Obtain the access_token with publish_stream permission
if(empty($code)){
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url
. "'</script>");
}
else {
$token_url="https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
// Show photo upload form to user and post to the Graph URL
$graph_url= "https://graph.facebook.com/me/photos?"
. "access_token=" .$access_token;
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.$graph_url .' "method="POST">';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message"
type="text" value=""><br/><br/>';
echo '<input type="submit" value="Upload"/><br/>';
echo '</form>';
echo '</body></html>';
}
?>
Sample Output:
{
"id": "1001207389476"
}
Documentation: https://developers.facebook.com/docs/reference/api/photo/
Hope this helps!
I have the following code which works fine as long as in a previous part of the application, the user accepts the applications request to publish_stream.
# The facebook library
require_once("/var/www/facebook-php-sdk-master/src/facebook.php");
# Create facebook object
$config = array();
$config['appId'] = 'appId_here';
$config['secret'] = 'secret_here';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
#check permissions
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $user_id,
'ext_perm' => 'publish_stream'
);
#set to true if true...
$can_offline = $facebook -> api( $api_call );
#is it true?
if( $can_offline ) {
$post = array(
'message' => 'post_a_message'
);
$facebook->api('/' . $_GET["id"] . '/feed', 'POST', $post);
} else {
// can't post message - don't have permission
}
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
} else {
error_log("user not logged in");
exit;
}
To try to resolve this, I attempted to insert the following code into the else statement which currently in the code above only contains the comment // can't post message - don't have permission
The code I tried to insert into that else was this:
$loginUrl = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
header("Location: ".$loginUrl);
That works as long as the user accepts to allow my app to publish_stream. However, if the user does not accept, my app will keep asking the user to accept publish_stream. How do I stop that loop from happening if the user decides not to accept?
As far as i remember, $facebook -> getLoginUrl can take parameter cancel_url, which contains the link, where user should be redirected if he doesn't give your app permissions.
So the code will be something like this
$login_url = $facebook -> getLoginUrl( array(
'scope' => 'publish_stream',
'cancel_url' => YOUR_LINK_HERE
));
Here is the working code : Please check it :
Page name : events.php
You can see $redirect_uri = https://localhost/facebook_page/events.php it is returning back to same page.
<?php
$facebook_appid = "your appid"; // Facebook appplication id
$facebook_secret = "your app secret"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "publish_stream"; // User permission for facebook
$profile_id = "profile_id";// Where do you want to post it(profile id - It is a number)
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = rand(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
?>
<!-- Here you can use
message, picture, link, name, caption, description, source, place, tags
as input fields-->
<form enctype="multipart/form-data" method="POST" action="https://graph.facebook.com/<?php echo $profile_id;?>/feed?access_token=<?php echo $access_token; ?>">
<input type="text" name="message" value="test" />
<input type="submit" name="submit" value="Submit" />
</form>
You can post it using jquery also.
I use the following code to check if the user has allowed publishing permisions or not:
$permissions = $facebook->api('me/permissions');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
//Continue with posting on users wall
} else {
//Continue without posting on users wall
}
I am creating an app where the user can upload an image, that will be stored in apps profile page, and in the user profile. I'm using below code to do this work
<?php
$app_id = "XXXXXXXXXXXXXXXX";
$app_secret = "XXXXXXXXXXXXXXXXXXXXXXXX";
$post_login_url ="XXXXXXXXXXXXXXXXXXXXXXX";
$code = $_REQUEST["code"];
//Obtain the access_token with publish_stream permission
if(empty($code)){
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url
. "'</script>");
}
else {
$token_url="https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
// first get your album id, let's assume you need to create it
// create this before hand and you can just reference the id
$attachment = array('access_token'=> ACCESS_TOKEN, 'name'=>$ablum_name);
try{
$album_resp = $facebook->api("/{$this->page_id}/albums", 'POST', $attachment);
}catch(Exception $e){
throw new Exception("Failed to create album: ". $e->getMessage());
}
$album_id = $album_resp['id'];
// Show photo upload form to user and post to the Graph URL
$graph_url= "https://graph.facebook.com/photos?"
. "access_token=" .$access_token;
echo '<form enctype="multipart/form-data" action="'
.$graph_url .' "method="POST">';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message"
type="text" value=""><br/><br/>';
echo '<input type="submit" value="Upload"/><br/>';
echo '</form>';
}
?>
With this code it is going to the user's profile but not to the app's profile page. Can any one please tell what is wrong with it? Or is there another way to do it?
new to php please forgive my silly questions.
I am creating my first fb app. It allows user to browse through their local drive and select a photo. Once it is submit, it will redirect to the next page and process to the storing onto my server first then posting to user's wall.
The application is not working really that much. The part where user browse and app storing the photo on to my server is working, but it fails to grab the photo back from my server and post it on the user's wall.
config.php:
<?php
require_once 'facebook.php';
$app_id = "";
$app_key = "";
$app_secret = "";
$canvas_url = "";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$session = $facebook->getSession();
if (!$session) {
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'publish_stream, user_photos, read_stream, read_friendlists'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}//end if session user
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 />" ;
echo "<img src='https://graph.facebook.com/".$uid."/picture'/>";
}//end try getUser
catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}//end catch getUser
}//end else user
index.php contains the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
uploader.php run the process
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded" . "<br />";
} else{
echo "There was an error uploading the file, please try again!" . "<br />";
}
try {
$post_id = $facebook->api("/".$uid."/feed", "post", array("picture"=>$target_path));
if(isset($post_id))
echo "A new post to your wall has been posted with id: $post_id";
} catch (FacebookApiException $e) {
error_log($e);
}
I have been trying many different ways which i could find online but it does not work. i have tried adding $facebook->setFileUploadSupport(true); but receive errors.
Please advice me how i could go about getting to upload the photo onto the user wall.
Thank you very much
Hello bro this code works for me exactly. what this code you do, it will post the post into your album nor in application album.
if(isset($_POST['upload']))
{
if ( isset($_FILES["file"]) && $_FILES["file"]["error"]==0 )
{
$file='images/'.$_FILES["file"]['name'];
if( move_uploaded_file($_FILES["file"]["tmp_name"],$file))
{
$facebook->setFileUploadSupport(true);
$post_data = array(
'name'=>$_POST['album'],
'description'=>$_POST['album']
);
$data['album'] = $facebook->api("/me/albums", 'post', $post_data);
//$file = $file_name;
$post_data = array(
"message" => $_POST['message'],
"source" => '#' . realpath($file)
);
$album_id = $data['album']['id'];
$data['photo'] = $facebook->api("/$album_id/photos", 'post', $post_data);
}
}
/**/
}
When you upload any picture from your application, facebook creates an album into your profile named as your application. But this code will post the picture into your album. $_POST['album'] is the album name which I enter in a textfield. Then I just post the form and uploads photo. I hope this will help you
I think this should work:
$target_folder = "uploads/";
$target_path = $target_folder . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded" . "<br />";
$file_path = $target_folder . $_FILES['uploadedfile']['name'];
$arr = array();
$arr["image"] = '#' . realpath($file_path);
try {
$post_id = $facebook->api("/".$uid."/feed", "post", $arr);
if(isset($post_id))
echo "A new post to your wall has been posted with id: $post_id";
} catch (FacebookApiException $e) {
error_log($e);
}
} else{
echo "There was an error uploading the file, please try again!" . "<br />";
}
Replace getSession() with getUser()
because old PHP versions do not identify the getSession() function.
$session = $facebook->getSession();
use getUser();
Use This Code and It Will Work Fine For You as Facebook Documentation Here How-To: Use the Graph API to Upload Photos to a user’s profile Says
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$post_login_url = "YOUR_POST-LOGIN_URL";
$album_name = 'YOUR_ALBUM_NAME';
$album_description = 'YOUR_ALBUM_DESCRIPTION';
$code = $_REQUEST["code"];
//Obtain the access_token with publish_stream permission
if(empty($code))
{
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url .
"'</script>");
}
else {
$token_url= "https://graph.facebook.com/oauth/"
. "access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
// Create a new album
$graph_url = "https://graph.facebook.com/me/albums?"
. "access_token=". $access_token;
$postdata = http_build_query(
array(
'name' => $album_name,
'message' => $album_description
)
);
$opts = array('http' =>
array(
'method'=> 'POST',
'header'=>
'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($graph_url, false,
$context));
// Get the new album ID
$album_id = $result->id;
//Show photo upload form and post to the Graph URL
$graph_url = "https://graph.facebook.com/". $album_id
. "/photos?access_token=" . $access_token;
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.$graph_url. ' "method="POST">';
echo 'Adding photo to album: ' . $album_name .'<br/><br/>';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message" type="text"
value=""><br/><br/>';
echo '<input type="submit" value="Upload" /><br/>';
echo '</form>';
echo '</body></html>';
}
?>
Example Response
{
"id": "1001207389476"
}