Last few days I have been working on labs.9lessons to connecting Facebook Graph API access token system, it’s very interesting. This post I had presented in easy way to connect and read the Facebook home timeline with PHP and Jquery. Explained how to store facebook token and user id hope you like it. Thanks !
Download Script Live Demo
Database
Sample database table here storing facebook access token key and profile id. MySQL users table columns uid, uname, passcode, facebook_id and facebook_access_token
CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
passcode VARCHAR(50),
facebook_id VARCHAR(100),
facebook_access_token TEXT
);
(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
passcode VARCHAR(50),
facebook_id VARCHAR(100),
facebook_access_token TEXT
);
Demo Screencasting
Connecting Facebook
You have to create a facebook application. It will provide application_id and application_secret. While clicking Add Facebook anchor tag URL requesting Facebook Graph API with contains your web project redirection URL.
<a href="https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=APP_ID
&redirect_uri=http://yourwebsite.com/fbaccess.php
&scope=user_photos,user_videos,email,user_birthday,
offline_access,publish_stream,status_update">
Add Facebook
</a>
&redirect_uri=http://yourwebsite.com/fbaccess.php
&scope=user_photos,user_videos,email,user_birthday,
offline_access,publish_stream,status_update">
Add Facebook
</a>
Fbaccess.php
Redirecting file contains PHP code. Here you have to include facebook.php (Facebook library file) to getting the access token values. Updating users table where username=$user_session (login user).
<?php
# We require the library
require("facebook.php");
require("db.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET_ID',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session))
{
try
{
$facebook_id = $session['uid'];
$facebook_access_token=$session['access_token'];
// Updating Facebook values into Users table
mysql_query("UPDATE users SET facebook_uid='$facebook_id', facebook_access_token='$facebook_access_token' WHERE username='$user_session'");
header("Location: http://yourwebsite.com/home.php");
}
catch (Exception $e){}
}
else
{
header("Location: http://yourwebsite.com/home.php");
}
# We require the library
require("facebook.php");
require("db.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET_ID',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session))
{
try
{
$facebook_id = $session['uid'];
$facebook_access_token=$session['access_token'];
// Updating Facebook values into Users table
mysql_query("UPDATE users SET facebook_uid='$facebook_id', facebook_access_token='$facebook_access_token' WHERE username='$user_session'");
header("Location: http://yourwebsite.com/home.php");
}
catch (Exception $e){}
}
else
{
header("Location: http://yourwebsite.com/home.php");
}
Home.php
Contains HTML, Javascript and PHP code. Here using .getJSON to requesting Facebook Graph API home timeline with access_token and app_id.
<?php
include('db.php');
$sql=mysql_query("select facebook_id,facebook_access_token from users where username='$user_session'");
$row=mysql_fetch_array($sql);
$facebook_id=$row['facebook_id'];
$facebook_access_token=$row['facebook_access_token'];
?>
// Javascript Code-------------------------------------
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
$(".facebook").click(function()
{
var URL = 'https://graph.facebook.com/<?php echo $facebook_id; ?>/home?access_token=<?php echo $facebook_token; ?>&expires_in=0&callback=?';
$.getJSON(URL,function(data)
{
$.each(data.data, function(i,data)
{
var picture = 'http://graph.facebook.com/'+data.from.id+'/picture';
// If no message
if(data.message)
{
var msg=data.message;
}
else
{
var msg=data.name;
}
var div_data ="<div class='fb_status'><img src="+picture+" class='fb_image'/><a href='' ><b>"+data.from.name+"</b></a> "+msg+"</div>";
$(div_data).appendTo("#facebookdata");
});
});
</script>
// HTML Code---------------------------------------------
<?php
if($facebook_uid)
{
?>
<a href="#" class="facebook" >Connected</a>
<?php
} else {
?>
<a href="https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=APP_ID
&redirect_uri=http://yourwebsite.com/fbaccess.php
&scope=user_photos,user_videos,email,user_birthday,
offline_access,publish_stream,status_update">
Add Facebook
</a>
<?php
}
?>
<div id='facebookdata'></div>
include('db.php');
$sql=mysql_query("select facebook_id,facebook_access_token from users where username='$user_session'");
$row=mysql_fetch_array($sql);
$facebook_id=$row['facebook_id'];
$facebook_access_token=$row['facebook_access_token'];
?>
// Javascript Code-------------------------------------
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
$(".facebook").click(function()
{
var URL = 'https://graph.facebook.com/<?php echo $facebook_id; ?>/home?access_token=<?php echo $facebook_token; ?>&expires_in=0&callback=?';
$.getJSON(URL,function(data)
{
$.each(data.data, function(i,data)
{
var picture = 'http://graph.facebook.com/'+data.from.id+'/picture';
// If no message
if(data.message)
{
var msg=data.message;
}
else
{
var msg=data.name;
}
var div_data ="<div class='fb_status'><img src="+picture+" class='fb_image'/><a href='' ><b>"+data.from.name+"</b></a> "+msg+"</div>";
$(div_data).appendTo("#facebookdata");
});
});
</script>
// HTML Code---------------------------------------------
<?php
if($facebook_uid)
{
?>
<a href="#" class="facebook" >Connected</a>
<?php
} else {
?>
<a href="https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=APP_ID
&redirect_uri=http://yourwebsite.com/fbaccess.php
&scope=user_photos,user_videos,email,user_birthday,
offline_access,publish_stream,status_update">
Add Facebook
</a>
<?php
}
?>
<div id='facebookdata'></div>
CSS Code
.fb_status
{
min-height:60px;
padding:6px;
border-bottom:solid 1px #DEDEDE
}
.fb_status a
{
color:#3cf;
text-decoration:none
}
.fb_status a:hover{
color:#3cf;
text-decoration:underline
}
.fb_image{
float:left;
margin-right:14px;
width:50px;
height:50px;
padding:3px;
}
{
min-height:60px;
padding:6px;
border-bottom:solid 1px #DEDEDE
}
.fb_status a
{
color:#3cf;
text-decoration:none
}
.fb_status a:hover{
color:#3cf;
text-decoration:underline
}
.fb_image{
float:left;
margin-right:14px;
width:50px;
height:50px;
padding:3px;
}
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");
?>
$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");
?>
thanks for this! very helpful!
ReplyDeletevery nice
ReplyDeletewhat is the output of this script
ReplyDeleteits too good
ReplyDeleteThanks for the contribution. Unfortunately home.php does not log in; I think that the problem is in Fbaccess.php file,
ReplyDeleteSince in the mysql_query makes an UPDATE to something that does not get inserted and tries to update facebook_uid but this does not exist (UID). I am trying to print $user_session but his content is null ¿any idea? Greetings.
Very Good Post.... Keep Posting..
ReplyDeleteShashi Kanth.
yo, none of this matches up with your demo. or if it does, you're not providing some pieces. i was just trying out your oauth twitter demo and it was the same thing. whats up with that?
ReplyDeleteBrian Urban I am facing same problem. can any one post solution for that.
ReplyDeleteUsers table
ReplyDeletefacebook_id varchar(100)
Facebook message id's
Eg: 1194063517_106077952801531 storing like this.
But, what about the issues that Mark .Z will turn off facebook next March until forever?
ReplyDeleteDoes the facebook API which we use already would be a waste?
I hope not.
Thanks Srinivas
It's great post...
Regard from Olinklist
@Olinklist
ReplyDeleteFacebook shutdown is fake news
I just wonder why you store access_token in database ?
ReplyDeleteHi, great article though having trouble getting it to work, I have done all the above but because sessions are carried over when a user logs into my website I go to add Facebook, it bounces back and all the users profile information that would have been on display disappears, so it's destroying my session....
ReplyDeleteAny idea's..
Very important script you have shared really I have need of it.
ReplyDeleteJose
ReplyDeleteBrian Urban I am facing same problem. can any one post solution for that.
thanks for this great script, i am trying, but dont know why it cant save data into database, but i am trying to solve, hope it will work.
ReplyDeletethanks again.
Its not working properly dude :( please check, i am getting java scritp error, that "}" is expected on line 27, also the record on the database is not storing
ReplyDeleteWill it works on localhost?
ReplyDeleteNo..
ReplyDeleteI have a error by this:
ReplyDelete}
else
{
header("Location: http://...fbapp.../home.php");
}
Error:
Warning: Cannot modify header information - headers already sent by (output started at
an access token is appended when we move to home.php as home.php#access_token=...
ReplyDeletehow it is working? in fbaccess.php , there is no appending of access token. Access token that is append to home.php is different from $faceboo->getSession();
plz help me out
I did not get your point can you explain more about the problem.
ReplyDeleteI am having a problem as well...
ReplyDeleteI can click on "Add Facebook" and it will request access, and allow me to add the app to facebook, but then during the fbaccess.php page, it fails. It just adds:
fbaccess.php#access_token=#'s|#'s|MixOfLettersjo&expires_in=0
(#'s are my app id some other random number)
any idea as to why?
Thanks in advance.
Adam W
([email protected] is my email if there are any solutions to this! Appreciate it fellas!)
Hello Tamada why you save in db isn't it ok to store then session.
ReplyDeleteis this use in latter use.
can't the Java to render the facebook News Feed. I have DB connection but is shows no Java.
ReplyDeletewhere is the query that insert into users table?
ReplyDeletehow can we update without insert it first..
1. can't download the scripts
ReplyDelete2. why is it not possible in locahost?...i ve added to the facebook application settings , siteURL as http://localhost....won't that work??
Well, this looks really good and interesting, but can't make it work on my own... I see all your portions of code, some are incomplete (fbaccess.php missing closing php tag)...
ReplyDeleteI would really like to get a zip or something to download.
I copied your files, created App in facebook, modified all configurations, now home.php shows blanck, and $facebook_uid is always empty.
Also where are you inserting row into the database ? All I see is an update statement no insert anywhere.
Please help me clarify these points.
(April 2011) thanks,
@Dave
ReplyDeleteWhat was the exact problem in download script, let me know I will modify.
@Kabeen
ReplyDeleteFacebook app supporting live domains
I agree...I'm unable to locate the part of the script that tells you where to INSERT rather than UPDATE into the database. I feel there are parts missing
ReplyDeletecan you please help me to solve my problem?
ReplyDeletehere my problem is:
when i click "add facebook", it takes me to another page, and the page says:
{
"error": {
"type": "OAuthException",
"message": "Error validating application."
}
}
can you please help me?
you can send the answer to my email: [email protected]
thanks before :)
Why cant we download the files? You only let us get facebook.php which we could get right from their site.
ReplyDeleteSrinivas I'm trouble it's now allowing me to add facebook. It's just loading into the same home.php page.
ReplyDeleteAs many others have pointed out, this code does not INSERT into the database, so, this code does nothing.
ReplyDeleteGreat tutorial!!
ReplyDeletei need who to create app on facebook
ReplyDelete$session = $facebook->getSession();
ReplyDeleteempty problem refresh null whats? $user_session
home?access_token= problem
ReplyDelete?({
"error": {
"type": "OAuthException",
"message": "An unknown error has occurred."
}
});
friends?access_token= token true
so what home undefined
i am using this on a live domain (on a shared hosting account), but using localhost as the database hostname. the connection to the database seems to be made, but when i click on "add to facebook" it does not write to the database. all settings are correct. It just takes me to home.php and has the link to 'add to facebook'
ReplyDeleteagain. please help
mysql_fetch_array() expects parameter 1 to be resource, boolean given
ReplyDeletePlease how do i get this: require("facebook.php");
ReplyDeleteHow can this be made so the facebook login pops up and redirects back to the page.
ReplyDeletehi nice script i m really thankful to you
ReplyDeletebut i m getting a problem. i m using a free hosting so curl in not available
and when i m executing after redirection i will get an empty session plz help me.
i m frm india only so if possible pls call me my number is 9543246247 else just mail me d solution
my mail id is [email protected]
Hi.. where I can find this?
ReplyDelete# We require the library
require("facebook.php");
Hi... I only get NULL as result of
ReplyDelete$session = $facebook->getSession();
why?
Hey Srinivas, i guess fb has changed something on their side, $session = $facebook->getSession(); is returning null. Any work around you can suggest? Thanks avinash!
ReplyDeleteHi Sri,
ReplyDeleteSince we are UPDATING the 'users' table, which is initially blank for me,i'm not able to update any records, hence nothing is saved anytime.
Could you suggest some improvements that i can implement so as to insert new rows ?
Plz help, awaiting response.
Yes Srinivas,
ReplyDeleteplz suggest how to fix this session thing. The $session is always NULL. Plz help.
Good!
ReplyDeletehi...In the fbaccess.php there is an error i find it..can u help me out...error message is
ReplyDeleteParse error: syntax error, unexpected...it is frrom the exception handling ,,,,any one of you can help me out
How to solve this
ReplyDelete"error": {
"message": "Invalid redirect_uri: Given URL is not allowed by the Application configuration.",
"type": "OAuthException"
}
code having some error ... any way we can make it running
ReplyDeletegr8 thanks
ReplyDeleteGreat to hear from you. I feel interesting to read your blog. Its really informative too..
ReplyDeletehow to access the likes and comments from a facebook webpage and store it in a database..!!!
ReplyDeleteshrinivas tamada....hey solve our query dear.... How to access the Likes and Comments from outside of facebook page and store in a database .......
ReplyDeleteHey Srini,
ReplyDeleteAwesome tutorial..:)
But the thing is that it not returning session dude...
Please help me out..
This is my code.I have to store the uid,name and access token of the user into my database.
ReplyDeleteHow is that possible?
Please help me out.I am just a college student,so I am not that aware of coding and techniques.So please reply me soon.
Thanks in Advance
{
ReplyDelete"error": {
"message": "Invalid redirect_uri: URL \u0e17\u0e35\u0e48\u0e43\u0e2b\u0e49\u0e21\u0e32\u0e44\u0e21\u0e48\u0e44\u0e14\u0e49\u0e23\u0e31\u0e1a\u0e2d\u0e19\u0e38\u0e0d\u0e32\u0e15\u0e08\u0e32\u0e01\u0e01\u0e32\u0e23\u0e01\u0e33\u0e2b\u0e19\u0e14\u0e04\u0e48\u0e32\u0e02\u0e2d\u0e07\u0e41\u0e2d\u0e1e\u0e1e\u0e25\u0e34\u0e40\u0e04\u0e0a\u0e31\u0e19",
"type": "OAuthException",
"code": 191
}
}
$facebook->getSession(); is returning nothing in fbaccess.php
ReplyDeleteSame issue ...
ReplyDelete$facebook->getSession(); is returning nothing in fbaccess.php
Hey Srini,
ReplyDeleteCould you please see if there is an issue in your code since $facebook->getSession(); is returning empty
Use GetUser() instead
ReplyDeletedoesnt insert anything to DB no tokens begin inserted into be DB
ReplyDeleteits not doing anything to DB no updates there no access token not userid no username
ReplyDeleteBy default in database there is no value to update what can i update through the update query with inserting any row.
ReplyDeleteAnother nice tuts
ReplyDeletePLease update your code as facebook is using now graph api2.2 which have restrictions to share your information with others
ReplyDelete