I have created a facebook app in last month.
I am trying to upload a video from my PHP code, but it throws an error that (#353) You must select a video file to upload. While I tried to upload the same video from my Facebook account directly and it gets uploaded properly.
I don't know what is wrong things that exists, PHP code is as below
$api="/me/videos";
$uploaded_videos=$facebook->api($api);
$video_file_path=$user_dir_abs_path."/NewProject20.mov";
if(file_exists($video_file_path))
{
echo "file exists...";
}else{
die("not exist");
}
$ret_obj = $facebook->api('/me/videos', 'POST', array(
'source' => '#' . $video_file_path,
'title' => "This is just a test",
'description' => 'test9000',
'privacy' => json_encode(array('value' => 'EVERYONE' )),
)
);
echo '<pre>'. $ret_obj.'</pre>';
Video I have uploaded is here
Document I refer to code is here
https://developers.facebook.com/blog/post/493/
https://developers.facebook.com/blog/post/608/
I have used following code as well, but I am getting that same error..
$id=$facebook->getUser(); /* UID of the connected user */
$api="/".$id."/videos";
echo "api -> $api";
/*$ret_obj = $facebook->api('/me/videos', 'POST', array(*/
$ret_obj = $facebook->api($api, 'POST', array(
'source' => '#' . $video_file_path,
'title' => "This is just a test",
'description' => 'test9000',
'privacy' => json_encode(array('value' => 'EVERYONE' )),
)
);
echo '<pre>'. $ret_obj.'</pre>';
From your comments, I got to know that you need to upload/post a video from your server to facebook, instead form posting method specified in documentation.
I don't know much about facebook-sdk, I would suggest you to use CURL method instead.
<?php
$app_id = "XXXXXXXXXXXXXX";
$app_secret = "XXXXXXXXXXXXXXXXXXXXXXX";
$my_url = "http://localhost/url_of_this_page.php";
$video_title = "Video title here";
$video_desc = "Video description here";
$code = $_REQUEST["code"];
if(empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url . "'</script>");
}
$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);
$post_url = "https://graph-video.facebook.com/me/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&". $access_token;
$ch = curl_init();
$data = array('name' => 'file', 'file' => '#'.realpath("ipad.mp4"));// use realpath
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($ch);
if( $res === false ) {
echo curl_error($ch);
}
curl_close($ch);
?>
As a response from facebooks, you'l get video id like:
{"id":"892161284142980"}
Have a look at https://developers.facebook.com/docs/graph-api/reference/v2.0/user/videos/#publish
Videos must be encoded as multipart/form-data and published to
graph-video.facebook.com instead of the regular Graph API URL.
If anyone is still having issue uploading videos via the facebook sdk4 api, the below code worked for me:
$file_name = "/absolute/path/to/file/in/directory";
$linkData = [
'source' => new \CURLFile($file_name, 'video/m4v'),
'message' => 'Your message',
];
$ret_obj = $facebook->api('/me/videos', 'POST', $linkData);
Related
I have this problem with my code, iam trying to upload an image to a users wall, but it give me following error:
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /var/www/parkourjams.dk/emilaagaard/customers/fbgen/core/facebook/base_facebook.php on line 1238
My code is:
<?php
session_start();
require 'facebook/facebook.php';
$app_id = "438648619527874";
$app_secret = "HIDDEN";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'fileUpload' => true,
'cookie' => true
));
$post_login_url = "http://emilaagaard.dk/customers/fbgen/core/test.php";
$code = $_REQUEST["code"];
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;
// curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
echo "Token: " . $access_token . "<br /><br />";
$graph_url= "https://graph.facebook.com/me/photos?"
. "access_token=" .$access_token;
// Post it!
$user = $facebook->getUser();
$args = array(
'message' => 'Photo Caption',
'image' => '#'.realpath("ac.png")
);
$user = $facebook->getUser();
$user_profile = $facebook->api('/me');
if ($user) {
print_r($user);
echo "Username: " . $user_profile['username'];
try {
// We have a valid FB session, so we can use 'me'
$data = $facebook->api('/me/photos', 'post', $args);
echo $data;
} catch (FacebookApiException $e) {
print $e;
}
} else {
echo "Dead user";
$loginUrl = $facebook->getLoginUrl();
print ', try login</script>';
}
echo '</body></html>';
}
?>
I really hope for someone out there can help me, iam tired and have probably code-blinded my self for staying up all night after a party to finish this.
Thanks!
if you are testing it on local server
insert
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
insert
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
$facebook->setAccessToken($access_token);
before $user = $facebook->getUser();
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.
It looks like the authentication bit when Facebook is sending code, state parameters through $_GET is not covered in PHP-SDK.
if(!empty($_GET['code']) && !empty($_GET['state']))
{
$response = file_get_contents('https://graph.facebook.com/oauth/access_token?' . http_build_query(array('client_id' => AY_FACEBOOK_APP_ID, 'client_secret' => AY_FACEBOOK_APP_SECRET, 'redirect_uri' => AY_FACEBOOK_TAB_URL, 'code' => $_GET['code'])));
// now check state and parse access token
ay($response);
}
Did I overlook something? If not, then what is the reason for not including it?
Please note that I did not ask to provide an example as DMCS and Luc Franken did so far.
Yes, the state and code parameters are discussed on http://developers.facebook.com/docs/authentication/ in the part about CSRF protection.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
$response = file_get_contents(
'https://graph.facebook.com/oauth/access_token?' . http_build_query(
array(
'client_id' => AY_FACEBOOK_APP_ID,
'client_secret' => AY_FACEBOOK_APP_SECRET,
'redirect_uri' => AY_FACEBOOK_TAB_URL,
'code' => $_GET['code']
)
)
);
// now check state and parse access token
ay($response);
That reads a bit better.
Now your question: It just works:
https://graph.facebook.com/oauth/access_token?client_id=1&client_secret=2&redirect_uri=3&code=1234
With this testing code:
echo 'https://graph.facebook.com/oauth/access_token?' . http_build_query(
array(
'client_id' => 1,
'client_secret' => 2,
'redirect_uri' => 3,
'code' => '1234'
)
);
Try to put the url in a variable, that will make life easier when debugging.
If you don't get anything in the code= part you might have values in the $_GET['code'] variable which won't be accepted by http_build_query since that function urlencodes the array data.
I am trying to create a PHP page that will create a photo album and upload a photo. So far, it authenticates and creates a photo album without any problem but I cant seem to get it to upload the photo. I keep getting the following error:
Warning: fopen(https://graph.facebook.com/yyyyyyyyyyyyyyyyy/photos?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /home/content/30/8734730/html/uploadPhoto.php on line 96
<html>
<head>
<title>Photo Upload</title>
</head>
<body>
<?php
$app_id = "xxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$post_login_url = "http://xyz.com/uploadPhoto.php";
$album_name = "Brand Image Productions";
$album_description = "Blah Blah event Photos";
$photo_source = 'C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg';
$photo_message = 'Here is the lighthouse';
$code = $_REQUEST["code"];
echo "code ==>" . $code . '<br/><br/>';
//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,user_photos";
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'];
echo "access_token ==>" . $access_token . '<br/><br/>';
// 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; //upload photo
echo "album_id ==>" . $album_id . '<br/><br/>';
// Upload the photo
$graph_url = "https://graph.facebook.com/" . $album_id . "/photos?access_token=" . $access_token;
echo "graph_url ==>" . $graph_url . '<br/><br/>';
echo "photo_message ==>" . $photo_message . '<br/>';
echo "photo_source ==>" . $photo_source . '<br/><br/>';
$postdata = http_build_query(
array(
'message' => $photo_message,
'source' => $photo_source
)
);
$opts = array('http' =>
array(
'method'=> 'POST',
'header'=> 'Content-type: application/x-www-form-urlencoded',
'enctype' => 'multipart/form-data',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$fp = fopen($graph_url, 'r', false, $context);
fpassthru($fp);
fclose($fp);
}
?>
</body>
</html>
I have the following code which I think is very close to working but I keep getting the following error:
{"error":{"message":"(#324) Requires upload file","type":"OAuthException"}}
but I cannot figure out how to specify the upload file... I have tried both image and source, both give the same error. Any thoughts, help, suggestions would be greatly appreciated as I have been struggling with this for a couple of days and it seems like it should not be this hard...
<html>
<head>
<title>Photo Upload</title>
</head>
<body>
<?php
$app_id = "MY APP ID GOES HERE";
$app_secret = "MY APP SECRET GOES HERE";
$post_login_url = "MY URL GOES HERE";
$album_name = "Test Album";
$album_description = "Blah Blah event Photos";
$photo_source = realpath("C:\\Users\\Public\\Pictures\\Sample Pictures\\Lighthouse.jpg");
$photo_message = 'Here is the lighthouse';
$code = $_REQUEST["code"];
echo "code ==>" . $code . '<br/><br/>';
//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,user_photos";
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'];
echo "access_token ==>" . $access_token . '<br/><br/>';
// 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; //upload photo
echo "album_id ==>" . $album_id . '<br/><br/>';
// Upload the photo
$args = array( 'message' => $photo_message,
'image' => $photo_source
);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$album_id.'/photos?
access_token='.$access_token;
echo "url ==>" . $url . '<br/><br/>';
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);
echo "data ==>" . $data . "<br>";
}
?>
</body>
</html>
You need to set the config var fileUpload to true when creating a new instance of the Facebook class as described in the documentation here and here. And you also need the photo_upload permission ;-)
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = true; // <-- set this to 'true' otherwise it won't work
$facebook = new Facebook($config);
You are using file name instead of file itself in your Graph API call.
You should prefix file name with #
$args = array( 'message' => $photo_message,
'image' => '#'.$photo_source
);