I have created an api to import photos from facebook and google+. But I am facing a problem in displaying the list of photos. Can you please resolve this?
My Code Below:
File Name: index.php (Google)
<?php
include_once "google-plus-access.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Google+ API To Fetch Photos</title>
<link rel='stylesheet' href='style.css' />
</head>
<body>
<div id="bar">
<div class="top-area" >
<div class="login" >
<?php if(isset($me) && isset($activities)) { ?>
<a href="?logout" ><h5>Logout</h5></a>
<?php } else { ?>
<a href="<?php echo($authUrl); ?>" ><h5>Login</h5></a>
<?php } ?>
</div>
</div>
</div>
<?php if(isset($me) && isset($activities)) {?>
<div class="big-container" >
<div class="profile" >
<div class="profile-pic" ><a href="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>" ><img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" /></a>
</div>
<div class="profile-info" >
<div class="name" ><a href="<?php echo($me['url']) ; ?>" ><?php if(isset($me['displayName'])) echo(strtoupper($me['displayName'])); else echo "Not set or private"; ?></a></div>
<div class="details" >
<ul>
<li><b>GENDER : </b><?php if(isset($me['gender'])) echo($me['gender']); else echo "Not set or private"; ?></li>
<li><b>ORGANISATION : </b><?php if(isset($me['organizations']['0']['name'])) echo($me['organizations']['0']['name']); else echo "Not set or private"; ?></li>
<li><b>PLACE : </b><?php if(isset($me['placesLived']['0']['value'])) echo($me['placesLived']['0']['value']); else echo "Not set or private"; ?></li>
</ul>
</div>
</div>
</div>
</div>
<?php foreach($activities['items'] as $activity): ?>
<div class="activity" >
<div class="title" ><a href="<?php echo($activity['object']['url']) ; ?>" ><?php echo($activity['object']['content']); ?></a></div>
<p>Published at <?php echo($activity['published']); ?></p>
<p>
<?php echo($activity['object']['replies']['totalItems']); ?> Replies .
<?php echo($activity['object']['plusoners']['totalItems']); ?> Plusoners .
<?php echo($activity['object']['resharers']['totalItems']); ?> Reshares
</p>
</div>
<?php endforeach ?>
<br><br>
<div class="photos">
<?php
if(isset($me['url']))
{
$photos = "https://plus.google.com/photos/";//.$me['id']."/albums";
echo $photos;
}
?>
</div>
<?php } else {?>
<div class="login-box">
<div id="connect-button"><a href="<?php echo($authUrl); ?>" ><img src="connect-button.png" alt="Connect to your Google+ Account"/></a>
<div>This API is purely read-only. It will <b>NOT</b> post anything to your profile.
</div>
</div>
</div>
<?php } ?>
</body>
</html>
File Name: google-plus-access.php
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';
session_start();
$client = new apiClient();
$client->setApplicationName("picpixa");
//*********** Replace with Your API Credentials **************
$client->setClientId('***********************');
$client->setClientSecret('************************');
$client->setRedirectUri('http://localhost/MyApi/Google-Plus/');
$client->setDeveloperKey('*********************************');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/photos'));
$plus = new apiPlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
File Name: index.php (Facebook)
<?php
include_once "fbmain.php";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Fetch Image From Facebook</title>
<script type="text/javascript">
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
FB.ui({method: 'feed',
message: userPrompt,
link: hrefLink,
caption: hrefTitle,
picture: 'http://thinkdiff.net/ithinkdiff.png'
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
}
function publishStream() {
streamPublish("Stream Publish", 'Checkout personalized products at www.picpixa.com. I found some of them are just awesome!', 'Checkout www.picpixa.com', 'http://www.picpixa.com', "Personalized Products");
}
function newInvite() {
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'Come on checkout Personalized Products. visit http://www.picpixa.com',
},
function(receiverUserIds) {
console.log("IDS : " + receiverUserIds.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
</script>
</head>
<body>
<style type="text/css">
.box{
margin: 5px;
border: 1px solid #60729b;
padding: 5px;
width: 500px;
height: 200px;
overflow:auto;
background-color: #e6ebf8;
}
</style>
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: '<?= $fbconfig['appid'] ?>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
</script>
<?php if (!$user) { ?>
You have to login using Facebook Login Button to see api calling result.
<img src="Images/login.png">
<?php } else { ?>
<img src="Images/logout.png">
<?php } ?>
<!-- all time check if user session is valid or not -->
<?php if ($user) { ?>
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>
<!-- Data retrived from user profile are shown here -->
<div class="box">
<b>User Photos using Graph API</b>
<?php d($user_photos); ?>
</div>
</td>
</tr>
</table>
<?php }?>
</body>
</html>
File Name: fbmain.php
<?php
$fbconfig['appid'] = "Your App Id";
$fbconfig['secret'] = "Your App Secret";
$fbconfig['baseurl'] = "localhost/MyApi/Facebook/index.php";
//
if (isset($_GET['request_ids'])) {
//user comes from invitation
//track them if you need
}
try {
include_once "facebook.php";
} catch (Exception $o) {
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => false,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_photos',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user) {
//Retriving photos of user using graph api
try {
$user_photos = $facebook->api("/$user/photos");
} catch (Exception $o) {
d($o);
}
}
function d($d) {
echo 'This function is called <br><br><pre>';
print_r($d);
echo '</pre>';
}
?>
I am not sure what you expected on the Google+ side. All you are doing for photos, apparently, is printing the URL based on the Google ID. (Assuming the portion that was commented out.)
There is no way using the Google+ API to get the user's photos. You need to look into using the Picasa Web Albums Data API, but this is using Google's older GData protocol. There are a couple of resources that may help, for example, there is a PHP library which uses an older version of the protocol and a more modern example code snippet which may guide you in doing this.
You should star https://code.google.com/p/google-plus-platform/issues/detail?id=670 to indicate you want a more modern API for photos in Google+.
Related
I just built an app with the Facebook PHP SDK and set it up. I am testing it and though I get the image to show up from my profile, the user info requested is not showing up. Here is the screenshot of the results
Here is the php code that I uploaded to the server. Note that the App ID and Secret have been removed from here.
<?php
require ('src/facebook.php');
$app_id = " "; //has been removed
$secret = " "; //has been removed
$app_url = "http://apps.facebook.com/instahomework/";
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} 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();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk example 1 - user login and authorisation</title>
<style>
body { font-family: Helvetica, Verdana, Arial, sans-serif; }
a { text-decoration:none; }
a:hover { text-decoration:underline; }
</style>
</head>
<body>
<pre>
<?php print_r($_REQUEST); ?>
</pre>
<?php if ($user) { ?>
<h2>Welcome</h2>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture"><br/>
<?php echo $name; ?><br/>
<br/>
Gender : <?php echo $gender; ?><br/>
Locale : <?php echo $locale; ?><br/>
Username : <?php echo $username; ?><br/>
<?php } else { ?>
<strong><em>You have not granted this App permission to access your data. Redirecting to permissions request...</em></strong>
<?php } ?>
</body>
</html>
you should replace your HTML code with:
<h2>Welcome</h2>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture"><br/>
<?php echo $user_profile['name']; ?><br/>
<br/>
Gender : <?php echo $user_profile['gender']; ?><br/>
Locale : <?php echo $user_profile['locale']; ?><br/>
Username : <?php echo $user_profile['username']; ?><br/>
as the "user info" you want is requested by this line of code:
$user_profile = $facebook->api('/me');
and stored into the $user_profile array.
Another workaround (but not recommended) is using extract() to extract the data from facebook into your global variable scope, by adding this line of code:
extract($user_profile);
I needed to request permission to a facebook user to get specific informations (email,birthday).
When a user launches the application for the first time, if he accepts the permission, he is forced to refresh the page to display data (just informations concerning the user,see my code).
The problem is it works fine sometime,that's why i don't know if it is a facebook problem or a problem in my own code.
If you can have a look at my code, some help would be much appreciated!
thanks in advance
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '453976824647366',
'secret' => 'fe86f3b0b34b3ed6XXXXXX',
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<fb:login-button autologoutlink="true" perms="email,user_birthday" size="large" onlogin="window.location = 'youlike.php';">Connect to this application using Facebook</fb:login-button>
<?php if ($user): ?>
<h3>Vous</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<pre><?php print_r($user_profile); ?></pre>
Date de Naissance : <?php echo $user_profile["birthday"];
echo '<ul>';
foreach ($friends["data"] as $value) {
echo '<li>';
echo '<div class="pic">';
echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
echo '</div>';
echo '<div class="picName">'.$value["name"].'</div>';
echo '</li>';
}
echo '</ul>';?>
<?php endif ?>
</body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
</div>
<script>
FB.init({appId: '453976824647366', status: true,
cookie: true, xfbml: true});
</script>
</div>
</html>
You can always force a refresh on login/logout, just to be sure:
after your FB.init
FB.Event.subscribe('auth.login', function(){
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(){
window.location.reload();
});
I started a new PHP app on Facebook using Heroku. They start you out with a sample webpage that you can modify. When you first visit the page, it looks like this.
Where in index.php is the code for that log in button that you see in the upper left?
If you press that button, then you get this next page.
As you see, the app gets permissions for only 3 things (basic info, likes, photos). I want to add more permissions, but I could not find where this happens in the code. Where is it?
Here is the full source code for index.php.
<?php
/**
* This sample app is provided to kickstart your experience using Facebook's
* resources for developers. This sample app provides examples of several
* key concepts, including authentication, the Graph API, and FQL (Facebook
* Query Language). Please visit the docs at 'developers.facebook.com/docs'
* to learn more about the resources available to you
*/
// Provides access to app specific values such as your app id and app secret.
// Defined in 'AppInfo.php'
require_once('AppInfo.php');
// Enforce https on production
if (substr(AppInfo::getUrl(), 0, 8) != 'https://' && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
// This provides access to helper functions defined in 'utils.php'
require_once('utils.php');
/*****************************************************************************
*
* The content below provides examples of how to fetch Facebook data using the
* Graph API and FQL. It uses the helper functions defined in 'utils.php' to
* do so. You should change this section so that it prepares all of the
* information that you want to display to the user.
*
****************************************************************************/
require_once('sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
));
$user_id = $facebook->getUser();
if ($user_id) {
try {
// Fetch the viewer's basic information
$basic = $facebook->api('/me');
} catch (FacebookApiException $e) {
// If the call fails we check if we still have a user. The user will be
// cleared if the error is because of an invalid accesstoken
if (!$facebook->getUser()) {
header('Location: '. AppInfo::getUrl($_SERVER['REQUEST_URI']));
exit();
}
}
// This fetches some things that you like . 'limit=*" only returns * values.
// To see the format of the data you are retrieving, use the "Graph API
// Explorer" which is at https://developers.facebook.com/tools/explorer/
$likes = idx($facebook->api('/me/likes?limit=4'), 'data', array());
// This fetches 4 of your friends.
$friends = idx($facebook->api('/me/friends?limit=4'), 'data', array());
// And this returns 16 of your photos.
$photos = idx($facebook->api('/me/photos?limit=16'), 'data', array());
// Here is an example of a FQL call that fetches all of your friends that are
// using this app
$app_using_friends = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT uid, name FROM user WHERE uid IN(SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1'
));
}
// Fetch the basic info of the app that they are using
$app_info = $facebook->api('/'. AppInfo::appID());
$app_name = idx($app_info, 'name', '');
?>
<!DOCTYPE html>
<html xmlns:fb="http://ogp.me/ns/fb#" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes" />
<title><?php echo he($app_name); ?></title>
<link rel="stylesheet" href="stylesheets/screen.css" media="Screen" type="text/css" />
<link rel="stylesheet" href="stylesheets/mobile.css" media="handheld, only screen and (max-width: 480px), only screen and (max-device-width: 480px)" type="text/css" />
<!--[if IEMobile]>
<link rel="stylesheet" href="mobile.css" media="screen" type="text/css" />
<![endif]-->
<!-- These are Open Graph tags. They add meta data to your -->
<!-- site that facebook uses when your content is shared -->
<!-- over facebook. You should fill these tags in with -->
<!-- your data. To learn more about Open Graph, visit -->
<!-- 'https://developers.facebook.com/docs/opengraph/' -->
<meta property="og:title" content="<?php echo he($app_name); ?>" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo AppInfo::getUrl(); ?>" />
<meta property="og:image" content="<?php echo AppInfo::getUrl('/logo.png'); ?>" />
<meta property="og:site_name" content="<?php echo he($app_name); ?>" />
<meta property="og:description" content="My first app" />
<meta property="fb:app_id" content="<?php echo AppInfo::appID(); ?>" />
<script type="text/javascript" src="/javascript/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function logResponse(response) {
if (console && console.log) {
console.log('The response was', response);
}
}
$(function(){
// Set up so we handle click on the buttons
$('#postToWall').click(function() {
FB.ui(
{
method : 'feed',
link : $(this).attr('data-url')
},
function (response) {
// If response is null the user canceled the dialog
if (response != null) {
logResponse(response);
}
}
);
});
$('#sendToFriends').click(function() {
FB.ui(
{
method : 'send',
link : $(this).attr('data-url')
},
function (response) {
// If response is null the user canceled the dialog
if (response != null) {
logResponse(response);
}
}
);
});
$('#sendRequest').click(function() {
FB.ui(
{
method : 'apprequests',
message : $(this).attr('data-message')
},
function (response) {
// If response is null the user canceled the dialog
if (response != null) {
logResponse(response);
}
}
);
});
});
</script>
<!--[if IE]>
<script type="text/javascript">
var tags = ['header', 'section'];
while(tags.length)
document.createElement(tags.pop());
</script>
<![endif]-->
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo AppInfo::appID(); ?>', // App ID
channelUrl : '//<?php echo $_SERVER["HTTP_HOST"]; ?>/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Listen to the auth.login which will be called when the user logs in
// using the Login button
FB.Event.subscribe('auth.login', function(response) {
// We want to reload the page now so PHP can read the cookie that the
// Javascript SDK sat. But we don't want to use
// window.location.reload() because if this is in a canvas there was a
// post made to this page and a reload will trigger a message to the
// user asking if they want to send data again.
window.location = window.location;
});
FB.Canvas.setAutoGrow();
};
// Load the SDK Asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<header class="clearfix">
<?php if (isset($basic)) { ?>
<p id="picture" style="background-image: url(https://graph.facebook.com/<?php echo he($user_id); ?>/picture?type=normal)"></p>
<div>
<h1>Welcome, <strong><?php echo he(idx($basic, 'name')); ?></strong></h1>
<p class="tagline">
This is your app
<?php echo he($app_name); ?>
</p>
<div id="share-app">
<p>Share your app:</p>
<ul>
<li>
<a href="#" class="facebook-button" id="postToWall" data-url="<?php echo AppInfo::getUrl(); ?>">
<span class="plus">Post to Wall</span>
</a>
</li>
<li>
<a href="#" class="facebook-button speech-bubble" id="sendToFriends" data-url="<?php echo AppInfo::getUrl(); ?>">
<span class="speech-bubble">Send Message</span>
</a>
</li>
<li>
<a href="#" class="facebook-button apprequests" id="sendRequest" data-message="Test this awesome app">
<span class="apprequests">Send Requests</span>
</a>
</li>
</ul>
</div>
</div>
<?php } else { ?>
<div>
<h1>Welcome</h1>
<div class="fb-login-button" data-scope="user_likes,user_photos"></div>
</div>
<?php } ?>
</header>
<section id="get-started">
<p>Welcome to your Facebook app, running on <span>heroku</span>!</p>
Learn How to Edit This App
</section>
<?php
if ($user_id) {
?>
<section id="samples" class="clearfix">
<h1>Examples of the Facebook Graph API</h1>
<div class="list">
<h3>A few of your friends</h3>
<ul class="friends">
<?php
foreach ($friends as $friend) {
// Extract the pieces of info we need from the requests above
$id = idx($friend, 'id');
$name = idx($friend, 'name');
?>
<li>
<a href="https://www.facebook.com/<?php echo he($id); ?>" target="_top">
<img src="https://graph.facebook.com/<?php echo he($id) ?>/picture?type=square" alt="<?php echo he($name); ?>">
<?php echo he($name); ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
<div class="list inline">
<h3>Recent photos</h3>
<ul class="photos">
<?php
$i = 0;
foreach ($photos as $photo) {
// Extract the pieces of info we need from the requests above
$id = idx($photo, 'id');
$picture = idx($photo, 'picture');
$link = idx($photo, 'link');
$class = ($i++ % 4 === 0) ? 'first-column' : '';
?>
<li style="background-image: url(<?php echo he($picture); ?>);" class="<?php echo $class; ?>">
</li>
<?php
}
?>
</ul>
</div>
<div class="list">
<h3>Things you like</h3>
<ul class="things">
<?php
foreach ($likes as $like) {
// Extract the pieces of info we need from the requests above
$id = idx($like, 'id');
$item = idx($like, 'name');
// This display's the object that the user liked as a link to
// that object's page.
?>
<li>
<a href="https://www.facebook.com/<?php echo he($id); ?>" target="_top">
<img src="https://graph.facebook.com/<?php echo he($id) ?>/picture?type=square" alt="<?php echo he($item); ?>">
<?php echo he($item); ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
<div class="list">
<h3>Friends using this app</h3>
<ul class="friends">
<?php
foreach ($app_using_friends as $auf) {
// Extract the pieces of info we need from the requests above
$id = idx($auf, 'uid');
$name = idx($auf, 'name');
?>
<li>
<a href="https://www.facebook.com/<?php echo he($id); ?>" target="_top">
<img src="https://graph.facebook.com/<?php echo he($id) ?>/picture?type=square" alt="<?php echo he($name); ?>">
<?php echo he($name); ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
</section>
<?php
}
?>
<section id="guides" class="clearfix">
<h1>Learn More About Heroku & Facebook Apps</h1>
<ul>
<li>
Heroku
<p>Learn more about Heroku, or read developer docs in the Heroku Dev Center.</p>
</li>
<li>
Websites
<p>
Drive growth and engagement on your site with
Facebook Login and Social Plugins.
</p>
</li>
<li>
Mobile Apps
<p>
Integrate with our core experience by building apps
that operate within Facebook.
</p>
</li>
<li>
Apps on Facebook
<p>Let users find and connect to their friends in mobile apps and games.</p>
</li>
</ul>
</section>
</body>
</html>
The login button is created using javascript based on the attributes of the div below
<div class="fb-login-button" data-scope="user_likes,user_photos"></div>
you can add extra permissions to the comma separated list.
I'd like new users to be able to 'connect' with the use of the fb connect button on my site and once connected it will display their first+last name and profile picture.
If the user is already connected, the connect button turns into a logout.
Going by the docs, i've implemented the following code;
<html>
<head>
<title>test full name and photo</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:'xxxxxxxxxx', cookie:true,
status:true, xfbml:true
});
FB.api('/me', function(user) {
if(user != null) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
</script>
<div align="center">
<img id="image"/>
<div id="name"></div>
</div>
</body>
</html>
The only problem is that it does not display the facebook connect button and when I try and insert it, the code breaks.
Any help would be much appreciated!
recap: website checks if the user has connected and has a valid session, if not, display fb connect/login button, if yes, display the logout button, either way it should show the user their name and profile photo.
Thank you!
The Facebook PHP-SDK will do exactly what you want:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
// Session based API call.
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
// login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>test full name and photo</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>', // App ID
channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php if ($user): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<?php endif ?>
<?php if ($user): ?>
<div align="center">
<img id="image" src="https://graph.facebook.com/<?php echo $uid; ?>/picture" />
<div id="name"><?php echo $me['name']; ?></div>
</div>
<?php endif ?>
</body>
</html>
I wanted to include the facebook login inside my application. This is the sample code which I was provided with:
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'my api goes here',
'secret' => 'my api secret goes here',
'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!--
We use the JS SDK to provide a richer user experience. For more info,
look here: http://github.com/facebook/connect-js
-->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<h1>php-sdk</h1>
<?php if ($me): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<div>
Without using JavaScript & XFBML:
<a href="<?php echo $loginUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>
</div>
<?php endif ?>
<h3>Session</h3>
<?php if ($me): ?>
<pre><?php print_r($session); ?></pre>
<h3>You</h3>
<img src="https://graph.facebook.com/<?php echo $uid; ?>/picture">
<?php echo $me['name']; ?>
<?php echo $me['education'][0]['school']['name']; ?>
<h3>Your User Object</h3>
<pre><?php print_r($me); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
<h3>Naitik</h3>
<img src="https://graph.facebook.com/naitik/picture">
<?php echo $naitik['name']; ?>
</body>
</html>
Now - this works well but when I'm trying to include that in my code igniter view file it's not allowing me to login due to an error. In the code where it says 'my api goes here' and 'my api secret goes here' I'm obviously inserting my app data. Does any of you encountered similar issue? When I click login I'm getting this error: An error occurred with MY APP. Please try again later.
Can anyone help me with this one?
Have you tried any of these two CodeIgniter libraries for Facebook?
http://www.haughin.com/code/facebook/
http://brandonbeasley.com/blog/facebook-api-codeigniter/
UPDATE: Sadly these links are no longer valid.
My partner just made a library and indepth tut to help with this:
http://hitsend.ca/2010/10/facebook-connect-user-authentication-using-the-new-graph-api-in-codeigniter/
Let us know what you think. We needed it for our uses, and figured it was a common problem.
It uses the new graph api, not the old one. That solves A LOT of problems.
Let us know what you think.