i have a website where people can upload pictures to be rated/liked etc. I am developing a function where if they don't want to upload pictures they can import them from there Facebook account.
I can login/logout the user from Facebook using the PHP Graph API but i am not sure on the request i need to get the logged in persons photos. I have setup the login url to the user_photos permissions.
I had a feature like this a few years ago where i would use the FQL to query the images but now i am using the new Facebook v4 Graph API.
Any help will be appreciated.
FacebookSession::setDefaultApplication( 'ID', 'SECRET' );
$helper = new FacebookRedirectLoginHelper('URL');
$permissions = array(
'user_photos'
);
try {
if ( isset( $_SESSION['access_token'] ) ) {
// Check if an access token has already been set.
$session = new FacebookSession( $_SESSION['access_token'] );
} else {
// Get access token from the code parameter in the URL.
$session = $helper->getSessionFromRedirect();
}
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error.
print_r( $ex );
} catch( \Exception $ex ) {
// When validation fails or other local issues.
print_r( $ex );
}
if ( isset( $session ) ) {
// Retrieve & store the access token in a session.
$_SESSION['access_token'] = $session->getToken();
// Logged in
echo 'Successfully logged in!';
} else {
// Generate the login URL for Facebook authentication.
$loginUrl = $helper->getLoginUrl($permissions);
echo 'Login';
}
After user has made the login you can get photos like so:
FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);
$session = new FacebookSession($access_token);
$response = (new FacebookRequest($session, 'GET', '/me/photos?fields=source&limit=100'))->execute();
$object = $response->getGraphObject();
$arr = self::convertToAssoc($object);
put in the limit param your value.
here is how you convert the facebook-object:
public static function convertToAssoc($graphObject){
$arr = $graphObject->asArray();
if ( !array_key_exists('data', $arr) ){
$arr['data'] = '';
}
$arr_data = $arr['data'];
$data = [];
foreach($arr_data as $item){
$data[] = get_object_vars($item);
}
return $data;
}
Related
I have code like this:
$helper = new FacebookRedirectLoginHelper('http://MyAwesomeWebsite.com/' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
echo print_r($ex);
} catch( Exception $ex ) {
echo print_r($ex);
}
if ( isset( $session ) ) {
$request = new FacebookRequest( $session, 'GET', '/me?locale=en_US&fields=name,email' );
$response = $request->execute();
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email'); // To Get Facebook email ID
}
But every time $femail is null. Why? What I'm doing wrong?
When you log in the user, you have to pass along the email permission in the scope parameter.
So when you call your helper, also initialise a $permissions array:
$helper = new FacebookRedirectLoginHelper('http://MyAwesomeWebsite.com/' );
$permissions = ['email', 'public_profile'];
There should be $helper->getLoginUrl call in somewhere in your code. In that call you should pass the $permissions variable as the second parameter:
$loginUrl = $helper->getLoginUrl($placeYourCallbackURLHere, $permissions);
That asks the user explicitly for a permission to get the user's email. Note that the email can also be empty, if the user has:
Registered to Facebook via phone number (does not have email address in Faceebook)
Selected that they do not want to provide the email address at the login prompt.
So I've been playing around with the Facebook API and have found that it's not easy! It's very hard to get a grip of it all. So I've managed to get the users id, name, email, friends, movies, and music.
/me?fields=id,name,email, friends.limit(5), movies.limit(5), music.limit(5)
But I found that it doesn't actually return the most useful data. It will return the data in any random order. Which is annoying. I was wondering if there is a way to sort the Movies and Music based on the likes (Most likes to least likes)?
At this stage all I've been able to do is print the users data using print_f($graphObject, 1). It would be really usefull if I could sort the Movies and Music based on the likes those pages have.
I'll add my code so everyone can see where im upto with the FB api - As you'll see, not very far. But I want to get to know it a lot more. It's very useful!
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( 'App_ID','SECRET_KEY' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://localhost/PHP_Advanced/Facebook/' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest(
$session,
//Add permissions to this - All gets returned as json object
'GET', '/me?fields=id,name,email, friends.limit(5), movies.limit(5), music.limit(5)'
);
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
//Store basic user info to then put into database
$userID = $graphObject['id'];
$userName = $graphObject['name'];
$userEmail = $graphObject['email'];
echo "Hello ".$userName;
echo "hello " . $data;
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
?>
</body>
</html>
Use {likes, name} to return likes count along with movie/music data.
Eg:
me?fields=id,name,email,movies.limit(5){likes,name},music.limit(5){likes,name}
After that you can sort json data based on likes.
Sample code:
<?php
$output = '{"id":"100004827362122","name":"FirstName LastName","email":"email#domain.com","movies":{"data":[{"likes":725577,"name":"Canal D2M","id":"253861394671560"},{"likes":4514156,"name":"UTV Motion Pictures","id":"82457488277"},{"likes":48573,"name":"Unfreedom","id":"204640696244906"},{"likes":13677504,"name":"Star Wars","id":"263361123833008"},{"likes":246922,"name":"Shudh Desi Endings","id":"162737470589326"}],"paging":{"cursors":{"before":"MjUzODYxMzk0NjcxNTYw","after":"MTYyNzM3NDcwNTg5MzI2"},"next":"https://graph.facebook.com/v2.2/100004827362122/movies?pretty=0&fields=likes,name&limit=5&after=MTYyNzM3NDcwNTg5MzI2"}},"music":{"data":[{"likes":2215,"name":"WDL","id":"1472840169599887"},{"likes":113860,"name":"Daniel Waples - Hang in Balance","id":"161974437185126"},{"likes":229799,"name":"KEXP","id":"9054273111"},{"likes":1276105,"name":"The Movement","id":"253878101400547"},{"likes":13294164,"name":"Virgin Radio Lebanon","id":"275155342593810"}],"paging":{"cursors":{"before":"MTQ3Mjg0MDE2OTU5OTg4Nw==","after":"Mjc1MTU1MzQyNTkzODEw"},"next":"https://graph.facebook.com/v2.2/100004827362122/music?pretty=0&fields=likes,name&limit=5&after=Mjc1MTU1MzQyNTkzODEw"}}}';
$output = json_decode($output, true);
$movies = $output['movies']['data'];
function sortData($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
usort($movies, 'sortData');
echo "<pre>";
print_r($movies);
?>
i want to use http://graph.facebook.com/XXX in my site
how i do a php file that have use this system and show my facebook details when i enter the link?
XXX = userrname
i want that the site show the details of the facebook user that enter the site
i tried everything but nothing, i dont want to make ap like this:
<?php
session_start();
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
$api_key = 'FACEBOOK_APP_ID';
$api_secret = 'FACEBOOK_APP_SECRET';
$redirect_login_url = 'http://www.yoursite.com/somefolder/file.php';
// https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0/
// initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);
// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);
// First check if this is an existing PHP session
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from the existing PHP sesson
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
// validate the access_token to make sure it's still valid
if ( !$session->validate() ) $session = null;
} catch ( Exception $e ) {
// catch any exceptions and set the sesson null
$session = null;
echo 'No session: '.$e->getMessage();
}
} elseif ( empty( $session ) ) {
// the session is empty, we create a new one
try {
// the visitor is redirected from the login, let's pickup the session
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
// Facebook has returned an error
echo 'Facebook (session) request error: '.$e->getMessage();
} catch( Exception $e ) {
// Any other error
echo 'Other (session) request error: '.$e->getMessage();
}
}
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION['fb_token'] = $session->getToken();
// and create a new Facebook session using the cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
try {
// with this session I will post a message to my own timeline
$request = new FacebookRequest(
$session,
'POST',
'/me/feed',
array(
'link' => 'www.finalwebsites.com/facebook-api-php-tutorial/',
'message' => 'A step by step tutorial on how to use Facebook PHP SDK v4.0'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
// the POST response object
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$msgid = $graphObject->getProperty('id');
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (post) request error: '.$e->getMessage();
}
// now we create a second request to get the posted message in return
if ( isset ( $msgid ) ) {
// we only need to the sec. part of this ID
$parts = explode('_', $msgid);
try {
$request2 = new FacebookRequest(
$session,
'GET',
'/'.$parts[1]
);
$response2 = $request2->execute();
$graphObject2 = $response2->getGraphObject();
// the GET response object
echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (get) request error: '.$e->getMessage();
}
}
} else {
// we need to create a new session, provide a login link
echo 'No session, please login.';
}
// use this for testing only
//unset($_SESSION['fb_token']);
thanks,
mtj
I hope someone helps me with this puzzle.
I tested facebook login v4 on my localhost where it works just fine,
at first it also worked on my live server, but for a mysterious reason it no longer does.
When on my live server (http://www.zenmony.com/test.php) I click the OAuth link, and for some reason I get a 503 error, and facebook throws no exceptions, so there is no way to debug.
here is my code:
FacebookSession::setDefaultApplication( '738781846169261','*******ac965af67d8979be972655c');
$helper = new FacebookRedirectLoginHelper('http://www.zenmony.com/test.php');
//$helper = new FacebookRedirectLoginHelper('http://localhost/test.php');
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
$session = null;
print_r($e);
exit;
}
}
if ( !isset( $session ) || $session === null ) {
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
print_r($ex);
exit;
} catch( Exception $ex ) {
print_r($ex);
exit;
}
}
// see if we have a session
if (isset($session))
{
// save the session
$_SESSION['fb_token'] = $session->getToken();
$session = new FacebookSession( $session->getToken() );
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
exit;
}
else
{
// show login url
$link = $helper->getLoginUrl( array( 'email', 'user_friends' ) );//&display=popup
echo "LINK";
}
Apparently the scipt goes as far as $session = $helper->getSessionFromRedirect(); but throws no exceptions and I have the 503 error code.
Just in case, here are my facebook application settings:
Please, need any help!
I'm a new developper on Facebook Graph API. I have follow this tutorial : https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0. I have test once and it works. I have modify and retest and it's work. But, the next day, nothing... My session token for facebook have change and I don't know why and how.
There is my code :
// ALL includes and variables
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( $app_ID, $app_secret );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( $url );
// generate login url with scope, each permission as element in array
$loginUrl = $helper->getLoginUrl( array($access_right) );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$graphObject = (new FacebookRequest( $session, 'GET', '/me/accounts'))->execute()->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$page_token = $graphObject['data'][0]->access_token;
echo '<p>Page token : '.$page_token.'</p>';
$session = new FacebookSession($page_token);
/* make the API call */
$request = new FacebookRequest(
$session,
'POST',
'/'.$pageID.'/feed',
array (
'message' => 'This is a test message',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
My goal is just to put a message on my fan page, and it works the first time. Why the variable "$_SESSION['fb_token']" is now NULL ?? How I can make it work ?
Thanks for response !
Edit 1 :
I discovered that my session have change the CSRF title : 'fb_token' to 'FBRLH_state'. An idea about this change ?
Here is the content of a file I have that logs in users using the latest Facebook PHP-SDK 4.0.9 (I think).
<?php
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphUser.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
if (!isset($_SESSION['facebookUserId']) || !isset($_SESSION['facebookSession']) || !isset($_SESSION['facebookUserProfile'])) {
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication($appId,$appSecret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( $canvasUrl );
try {
$FBSession = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
if (!isset($FBSession)) {
// STEP ONE - REDIRECT THE USER TO FACEBOOK FOR AUTO LOGIN / APP APPROVAL
header('Location: ' . $helper->getLoginUrl());
exit();
} else {
$user_profile = (new FacebookRequest($FBSession, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
$_SESSION['facebookUserId'] = $user_profile->getID();
$_SESSION['facebookSession'] = $FBSession; // I DON'T THINK THIS ACTAULLY WORKS RIGHT
$_SESSION['facebookUserProfile'] = $user_profile;
}
}
I simply include this file as seen below.
include ('SimpleFacebookLogin.php');
I try to save the session and it doesn't save properly in the session so I think I am missing something as well but I can successfully log in after creating a session. I am just not sure how to access it again afterward. I hope this helps.
Actualy works! =) Session is saved on my pc with this piece of script.
I added session_start() and session_write_close() - maybe you missed those?