How to POST video to Facebook through Graph API using PHP - php

The code found in the documentation uses a <form method="POST" to post a video to a profile:
// 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>';
What's the cleanest way to post from a URL without using a form?

Assuming that you have already uploaded the video on your server...
$config = array();
$config['appId'] = 'appID';
$config['secret'] = 'secretID';
$config['fileUpload'] = true;
$config['cookie'] = true;
$facebook = new Facebook($config);
$facebook->setFileUploadSupport(true);
$video_details = array(
'access_token'=> 'user publish token',
'message'=> 'Test video!',
'source'=> '#' .realpath($videosPathOnServer)
);
$post_video = $facebook->api('/'.$usersFacebookID.'/videos', 'post', $video_details);
As far as I remember, by default all videos visibility is set to Friends and their Friends

Related

php script facebook (#100) No permission to publish the video

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

(#200) User does not have sufficient administrative permission for this action on this page

After 5 days of trial and error I am getting very close to what I want to do.
with one exception. my current code only works once.
here is the scenario,
I am trying to Add A Page Tab to a facebook page using facebook sdk.
my current code works in a way but it will only work for the first facebook page that was created in facebook and if I try to add a page tab for other pages, it will throw the following error:
(#200) User does not have sufficient administrative permission for this action on this page
i do not understand why this is happening. this error usually means that I do not have a page access token but if that was the case, my code won't/shouldn't work for the first page either but it does!
any chance someone could take a look at my current code to see what I am doing wrong?
any help would be appreciated.
my current code as follows:
This is the part to get the access token and also after form submission:
// Set Extended Access Token
if (isset($code)) {
$fb->setExtendedAccessToken();
//Get access short live access token
$accessToken = $fb->getAccessToken();
// Exchange token
$fb->api('/oauth/access_token', 'POST',
array(
'grant_type' => 'fb_exchange_token',
'client_id' => $appId ,
'client_secret' => $secret,
'fb_exchange_token' => $accessToken
)
);
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $appId
. "&client_secret=" . $secret
. "&code=" . $code
. "&redirect_uri=" . $returnurl;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
$attachment_1 = array(
'access_token' => $user_access_token
);
}
$result = $fb->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["page_id"] == $page_id) {
$page_access_token = $page["access_token"];
//echo $page_access_token;
break;
}
}
//$pageIds=$fb->api('/me/accounts');
//$pageAccessToken=$pageIds["data"][1]["access_token"];
if(isset($_POST['msg']) and $_POST['msg']!=''){
try{
$message = array(
'access_token' => $page_access_token,
'message' => $_POST['msg']
);
$posturl = '/'.$_POST['pageid'].'/feed';
$posturl2 = '/'.$_POST['pageid'].'/tabs';
$fb->api($posturl2, 'POST', array(
'app_id'=>'0000000000000000000000000',
'access_token'=>$page_access_token
));
$result = $fb->api($posturl,'POST', $message);
if($result){
echo 'Successfully posted to Facebook Wall...';
}
}catch(FacebookApiException $e){
echo $e->getMessage();
}
}
and this is how I populate the users pages in a form within my page:
if(empty($pages)){
echo 'The user does not have any pages.';
}else{
echo '<form action="" method="post">';
echo 'Select Page: <select name="pageid">';
echo '<option value="">Select A Page</option>';
foreach($pages as $page){
echo '<option value="'.$page['page_id'].'">'.$page['name'].'</option>';
}
echo '</select>';
//echo 'Select Page: <select name="pageid2">';
// foreach($pageIds as $pageId){
// echo '<option value="'.$page['page_id'].'">'.$pageAccessToken.'</option>';
// }
//echo '</select>';
echo '<br />Message: <textarea name="msg"></textarea>';
echo '<br /><input type="submit" value="Post to wall" />';
echo '</form>';
}
}catch(FacebookApiException $e){
echo $e->getMessage();
}
I just had the same error message with a Realtime API subscription. I assume it´s the same problem, you don´t have Admin rights for the Page. You can still get a Page Token for a Page if you are Moderator (for example), but certain things are not possible if you are not Admin (Subscribing to the Realtime API, adding a Tab).

How to modify the album/photo upload process?

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.

Redirect back to my web page after posting an image to my wall

I have a website with Facebook capabilities (Sending personal messages, posting to wall). I have a page with a form that posting an image to the users wall photos album.
My problem is that after posting the image (Posting the form) i'm redirected to this url:
https://graph.facebook.com/'ALBUM_ID'/photos?access_token=AAAEzcP64ySABAA3YYxBzRlrtUn..............
And in the browser I see this: (I removed the numbers for security)
{
"id": "ID NUMBER HERE",
"post_id": "POST ID NUMBER HERE"
}
How can I tell Facebook to redirct me back to my page.
My code is:
$app_id = APP_ID;
$app_secret = APP_SECRET;
$my_url = "MY_URL";
$page_id = "PAGE_ID"; // Set this to your APP_ID for Applications
$code = $_REQUEST["code"];
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_stream,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;
}
}
$ALBUM_ID = "ALBUM_ID";
// Show photo upload form to user and post to the Graph URL
$image_post = "https://graph.facebook.com/" . $ALBUM_ID . "/photos?"
. "access_token=" .$access_token;
$video_post = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=testTitle" . "&description=testDescription"
. "&access_token=". $access_token;
?>
<table align="center">
<tr>
<td>
<?php
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.image_post.' "method="POST">';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/>';
echo 'Say something about this photo: <br/>';
echo '<textarea id="fbText" name="message"
rows="4" cols="47">';
echo '</textarea><br/><br/>';
echo '<input type="submit" value="Upload"/><br/>';
echo '</form>';
echo '</body></html>';
}
?>
</td>
</tr>
<?php
I've tried adding &redirect_uri=" . urlencode($my_url) to the $image_post but that didn't change anything in the behavior and redirected me to the same page without going back.
Thanks.
You have 3 options as I see it:
1 . This only works if you don't care about the response coming back from facebook:
<iframe name="uploader" onLoad="locationChange(this)"></iframe>
<form method="POST" action="..." target="uploader">
...
</form>
funnction locationChange(ifrm) {
console.log("iframe location has changed to: ", ifrm.src);
}
The problem with that is that if the upload fails you won't be aware, meaning that you can not differentiate between a successful upload and a failed one.
The reason you can not read the data from the iframe is that your page has a different domain than of the iframe, and browsers block communication in this case due to the same origin policy.
2 . Upload the image to your server and then from php upload the image to facebook.
You can use this: Upload Photo To Album with Facebook's Graph API.
3 . You can upload the image using ajax, there are some techniques, for example: Ajax Image Upload without Refreshing Page using Jquery.

Facebook: php upload photo and post on wall

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"
}

Categories