9lessons programming blog
Loading Search
Thursday, September 29, 2011

Working with Facebook SDK Permissions.

Facebook is the new Web planet, nowadays it’s a part of human life. Facebook offering user data access via Graph API. This is very helpful for start-up web projects to quickly collecting people data. This post explains you how to request Facebook login, permissions,reading user data and updating Wall using Facebook SDK. Tutorial contains multiple demos try all these Thanks!.

Login with Facebook

The tutorial contains lib directory contains facebook sdk and database config files with PHP files.
lib
-- facebook.php  //Facebook SDK
-- base_facebook.php 
-- fbconfig.php //Facebook Application configuration
-- db.php //Database connection
fblogin.php
home.php
status_update.php

Database
Sample database users table columns id,facebook_id, name, email etc..
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
facebook_id INT(20),
name VARCHAR(200),
email VARCHAR(200),
gender VARCHAR(10),
birthday DATE,
location VARCHAR(200),
hometown VARCHAR(200),
bio TEXT,
relationship VARCHAR(30),
timezone VARCHAR(10),
access_token TEXT
);

Facebook Application
You have to create a application. Facebook will provide you app id and app secret id, just replace in the following code.
fbconfig.php
<?php
$facebook_appid='App ID';
$facebook_app_secret='App Secret';
$facebook = new Facebook(array(
'appId' => $facebook_appid,
'secret' => $facebook_app_secret,
));
?>

fblogin.php
Facebook log in request for user details. Just a take a look at the scope, here requesting email and birthday. Storing $userdata value into session $_SESSION['userdata']
<?php
require 'lib/db.php';
require 'lib/facebook.php';
require 'lib/fbconfig.php';

$user = $facebook->getUser();
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
try
{
$userdata = $facebook->api('/me');
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
$_SESSION['facebook']=$_SESSION;
$_SESSION['userdata'] = $userdata;
$_SESSION['logout'] = $logoutUrl;
//Redirecting to home.php
header("Location: home.php");
}
else
{
$loginUrl = $facebook->getLoginUrl(array(
 'scope' => 'email,user_birthday'
));
echo '<a href="'.$loginUrl.'">Login with Facebook</a>';
}
?>

Basic User Information Demo

Download Script     Live Demo



home.php
Parsing Facebook user details $userdata array values and inserting into users table.
<?php
require 'lib/db.php';
require 'lib/facebook.php';
require 'lib/fbconfig.php';
session_start();
$facebook=$_SESSION['facebook'];
$userdata=$_SESSION['userdata'];
$logoutUrl=$_SESSION['logout'];
//Facebook Access Token
$access_token_title='fb_'.$facebook_appid.'_access_token';
$access_token=$facebook[$access_token_title];
if(!empty($userdata))
{
$facebook_id=$userdata['id'];
$name=$userdata['name'];
$first_name=$userdata['first_name'];
$last_name=$userdata['last_name'];
$email=$userdata['email'];
$gender=$userdata['gender'];
$birthday=$userdata['birthday'];
$location=mysql_real_escape_string($userdata['location']['name']);
$hometown=mysql_real_escape_string($userdata['hometown']['name']);
$bio=mysql_real_escape_string($userdata['bio']);
$relationship=$userdata['relationship_status'];
$timezone=$userdata['timezone'];
mysql_query("INSERT INTO `users` (`facebook_id`, `name`, `email`, `gender`, `birthday`, `location`, `hometown`, `bio`, `relationship`, `timezone`, `access_token`)
VALUES('$facebook_id','$name','$email','$gender','$birthday','$location','$hometown','$bio','$relationship','$timezone','$access_token')";

// Update or Post Facebook wall. 
include('status_update.php');
}
else
{
header("Location: fblogin.php");
}
?>

status_update.php
Update Facebook Wall using access_token via Graph API. Log in scope should be status_update take a look at the Post to my Wall code.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$status=$_POST['status'];
$facebook_id=$userdata['id'];
$params = array('access_token'=>$access_token, 'message'=>$status);
$url = "https://graph.facebook.com/$facebook_id/feed";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
echo "Message Updated";
}
?>
//HTML Code
<form method="post" action="">
<textarea name="status"></textarea> <br/>
<input type="submit" value=" Update "/>
</form>

Post to my Wall
Facebook log in scope for updating Facebook wall.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,user_birthday,status_update'
));
echo '<a href="'.$loginUrl.'">Login with Facebook</a>';

Status Update Demo

Download Script     Live Demo



Note: Above cases access_token value not static, it's depends on Facebook login session.

Facebook Offline Data Access
Here access_token is static, you can store this into users table. Any time you can do access or update Facebook using this access_token key. But facebook log out would't support so that you have to build native log out system for clearing sessions values as $userdata.

Offline Post to my Wall
Here any time you can update the Facebook wall. Just notice Access my data any time in following screen shot.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,user_birthday,status_update,offline_access'
));
echo '<a href="'.$loginUrl.'">Login with Facebook</a>';

Offline Access Demo

Download Script     Live Demo

9lessons labs is offline access.



Facebook Full Permission
Here I have requested full available scope to Facebook, based on your web project requirement you can select the user permission values. For more information about Facebook permissons read this link.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_about_me,user_activities,user_birthday,user_checkins,user_education_history,user_events,user_groups,user_hometown,user_interests,user_likes,user_location,user_notes,user_online_presence,user_photo_video_tags,user_photos,user_relationships,user_relationship_details,user_religion_politics,user_status,user_videos,user_website,user_work_history,email,read_friendlists,read_insights,read_mailbox,read_requests,read_stream,xmpp_login,ads_management,create_event,manage_friendlists,manage_notifications,offline_access,publish_checkins,publish_stream,rsvp_event,sms,publish_actions,manage_pages'
));
echo '<a href="'.$loginUrl.'">Login with Facebook</a>';

Full Access Demo

Live Demo



logout.php
Native log out sessions destroy.
<?php
session_start();
$user='';
$userdata='';
session_destroy();
header("Location: fblogin.php");
?>?

db.php
PHP database configuration file
<?php
$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
Sponsored Links

Share this post

Comments
{ 49 comments }
Oscar David Flórez Hernández said...

Awesome Script!!! Thank you so much.

Stretch said...

Great Stuff! Great Stuff! Great Stuff! Thanks

Anonymous said...

LIKE!! super cool script!! thankz :)

Anonymous said...

Thank You! Really helpful tutorial. You have shown how to get data like name, birthday etc. but how can I also retrieve information about school (name, year etc.) and other items that are in array ?

Thanks !

Anonymous said...

Great tutorial, but can we have a tutorial on facebook like tagging friends in an image...it would be very helpful

Anonymous said...

Getting school information was simple :)

$education = $userdata['education'];
foreach($education as $edu) {
$school = $edu['school']['name'];
$year = $edu['year']['name'];
$type = $edu['type']['name'];

$conc = $edu['concentration'];
if($conc) {
foreach($conc as $concentration) {

$concentration = $concentration['name'];

}
}

/*echo $school.$year.$type.$concentration;*/

}

Andrei said...

Exactly what I was looking for. Can you do the same for the Google+ social network?

Dk Singh said...

Great bindas work it ;)

Dk Singh said...

Really Good Work ..

Anonymous said...

very good i like :D

Dennis said...

Thanks for your Script (-: One Question. How can i update my Status when i logout or will post 2 days later? I have all Data in my Database.

Stretch said...

Hey guys, line 11 of home.php -
$access_token=$facebook[$access_token_title];
- seems to give me an error, any ideas?

It says "Fatal error: Cannot use object of type Facebook as array"

Fcebook portal BG said...

Great job! Thaks to autors. Exelent!

Yogesh Saroya said...

Fatal error: Uncaught exception 'Exception' with message 'Facebook needs the CURL PHP extension.' in C:\wamp\www\Facebook_Twitter_Login\fbsdk_basic\basic\lib\base_facebook.php:19 Stack trace: #0 C:\wamp\www\Facebook_Twitter_Login\fbsdk_basic\basic\lib\facebook.php(18): require_once() #1 C:\wamp\www\Facebook_Twitter_Login\fbsdk_basic\basic\fblogin.php(5): require('C:\wamp\www\Fac...') #2 {main} thrown in C:\wamp\www\Facebook_Twitter_Login\fbsdk_basic\basic\lib\base_facebook.php on line 19


pls help....

Srinivas Tamada said...

@Yogesh

Enable CURL extension for PHP

Basheer said...

hello there,

$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_birthday'
));

what u mean by this email and birth day filed..
what value i will replace for this

Please help me

thanks in advance

Anonymous said...

Very helpful

Anonymous said...

Yogesh

how to Enable CURL extension for PHP in Zend Server ...

Satyajit Sadhukhan said...

Waoo!! gr8 tutorial

Anonymous said...

how can i do this with canvas?

Anonymous said...

Working with Facebook SDK Permissions. I can't logout account. What can i do???????????????

Anonymous said...

getting error while creating facebook application...cant verify your account...what does it mean..??..how do i solve????

Anonymous said...

I tried to run it, but I get...

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/content/50/8522650/html/9lessons/fblogin.php:3) in /home/content/50/8522650/html/9lessons/lib/facebook.php on line 37

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/50/8522650/html/9lessons/fblogin.php:3) in /home/content/50/8522650/html/9lessons/lib/facebook.php on line 37

Any hints?

Anonymous said...

This worked really well for tracking individual logins! I'd like to use this to set up accounts for users and include other values, like game points. Should I simply get rid of the auto-incrementing ID, or will I still run into trouble with the SQL tables? Thanks!!

Anonymous said...

i have a solution for your headers already send problem... you have whitespace before the in your PHP code. I struggled with this for several hours. Fix fblogin.php first.

http://forum.mamboserver.com/showthread.php?t=42814

Anonymous said...

Hi Srinivash,

I want to access all the contacts detail of my friends from my gmail account just by giving an email id and password using PHP and JQuery..

itswadesh@gmail.com

Anonymous said...

hi , i am subscribed member of u r emails. i want to ask how to post user activity of our site to their facebook profile.

for example , now a days everybody is using Washington post social reader on facebook . when the user sign in for washigton post , washigton post updates that user profile that the given user is reading their articles which also appears in their friends news feed. So how to do that . Email me at vishal.seven7@gmail.com

Pawan Sharma said...

Hi Srinivash,

Below error coming after the login :

"An error occurred with Pawan. Please try again later."

Thanks
Pawan Sharma

Ashutosh joshi said...

hello srinivash. I like this article. but will it be totally secure to login through facebook? because now a days there are many hacking attacks happening in facebook.

YaMaKaZii said...

So cool dude

Lalit said...

Hey dude.. Its superlike script for facebook permission... But I am little bit confuse about how to get friends email id's.... Is it possible??
If yes then please tell me some thing good way to find it out...

Anonymous said...

hey some error when login redirect the same page not in home page why? anybody know please help me

Venkat said...

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/..../status_update/fblogin.php:3) in /home/.../status_update/lib/facebook.php on line 37

shows this error and redirect to the same page...

Anonymous said...

Hey where this lib/facebook.php

Warning: require(lib/facebook.php) [function.require]: failed to open stream: No such file or directory in C:\wamp\www\FB\fblogin.php on line 3

Fatal error: require() [function.require]: Failed opening required 'lib/facebook.php' (include_path='.;C:\php5\pear') in C:\wamp\www\FB\fblogin.php on line 3

GOODFATHER said...

can you help me, how to create NOTEs using Facebook SDK ?

I can read note written by my friend, and with public setting.
but I can't read from non-friend or private setting, right?

This is My code to read note
---------------------------------------
$fql = "SELECT uid, note_id, title, content_html, content, created_time, updated_time FROM note WHERE note_id=$note_id";
$params = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => '',
'access_token' => $facebook->getAccessToken()
);

$result = $facebook->api($params);
--------------------------------------------


Now, how to create a note ? confused :(
Example pleasee...

Punjabi said...

How to solve this error?
I just found this error when using Google Chrome, but if I use Firefox, my facebook app running normally and no error appear.

Fatal error: Uncaught Exception: 102:
Requires user session thrown in /home/XXXX/public_html/my_app/fb/base_facebook.php on line 1040

Tompa said...

How to delete a status ?

ari'sblog said...

why, after complete login into facebook, fblogin.php not redirect into home.php?

Pugazhwoo said...

It works for me but it returns nothing and it does't redirect to home.php.

George P. Theodotou said...

Hi Srinivas,

Quick question, in "access my data anytime" mode... how do I then display the users info (specifically FB pic) throughout my website?

Thanks

George

Dennis said...

hey (-:

how can i get tzhe user likes?
for example -> all music likes.
i tried it with $userdata['likes'] & $userdata['music'], but it dont work )-:

Reena said...

Hi Srinivas,
I created app on facebook, had provided app ID and app secret, but when I clicked on sign in to facebook link , I got an error sayin:

An error occurred with esprit. Please try again later.

API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.

Srinivas Tamada said...

@Reena

Try with registered live URL. Localhost it will not work.

dev said...

Fatal error: Uncaught exception 'Exception' with message 'Facebook needs the CURL PHP extension.' in C:\xampp\htdocs\basic\lib\base_facebook.php:19 Stack trace: #0 C:\xampp\htdocs\basic\lib\facebook.php(18): require_once() #1 C:\xampp\htdocs\basic\fblogin.php(5): require('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\basic\lib\base_facebook.php on line 19

dev said...

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\basic\fblogin.php:3) in C:\xampp\htdocs\basic\lib\facebook.php on line 37

Pankaj Kumar Jha said...

Can you help me, how we get friend list using Facebook SDK ?

My Code is as:

$url="https://graph.facebook.com/".$userdata['id']."/friends?access_token=".$access_token;


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

I am getting error:

{"error":{"message":"(#200) Permissions error","type":"OAuthException"}}

Anonymous said...

Hi ,
i want that facebook login page should be open in popwindow.
I some one can help me . .. . ?

Anonymous said...

Hello, can someone pls provide a code with a popup windows for login instead opening in the same window?

Anonymous said...

Hello, the logout you provided doesnt work as it should, it doesnt kill the sesion and doesnt logout from facebook
?

can u pls modifiy this?

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension