9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Tuesday, January 25, 2011

Facebook Graph API Connect with PHP and Jquery

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 !

Facebook Graph API connection PHP

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
);

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>

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");
}

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>

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;
}

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");
?>

Comments
{ 69 comments }
fsharing said...

thanks for this! very helpful!

මියුරංග said...

very nice

Anonymous said...

what is the output of this script

Anonymous said...

its too good

Brian Urban said...

Thanks for the contribution. Unfortunately home.php does not log in; I think that the problem is in Fbaccess.php file,
Since 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.

dskanth said...

Very Good Post.... Keep Posting..
Shashi Kanth.

jalbertbowdenii said...

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?

php development india said...

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Anonymous said...

Brian Urban I am facing same problem. can any one post solution for that.

Srinivas Tamada said...

Users table

facebook_id varchar(100)

Facebook message id's
Eg: 1194063517_106077952801531 storing like this.

Olinklist said...

But, what about the issues that Mark .Z will turn off facebook next March until forever?
Does the facebook API which we use already would be a waste?
I hope not.

Thanks Srinivas
It's great post...

Regard from Olinklist

Srinivas Tamada said...

@Olinklist

Facebook shutdown is fake news

Anonymous said...

I just wonder why you store access_token in database ?

Anonymous said...

Hi, 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....

Any idea's..

Domain Names Australia said...

Very important script you have shared really I have need of it.

José Chavez said...

Jose
Brian Urban I am facing same problem. can any one post solution for that.

BD Web Solutions said...

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.

thanks again.

Anonymous said...

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

Anonymous said...

Will it works on localhost?

Srinivas Tamada said...

No..

michi-ffm said...

I have a error by this:

}
else
{
header("Location: http://...fbapp.../home.php");
}


Error:
Warning: Cannot modify header information - headers already sent by (output started at

Anonymous said...

an access token is appended when we move to home.php as home.php#access_token=...
how 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

Srinivas Tamada said...

I did not get your point can you explain more about the problem.

Anonymous said...

I am having a problem as well...

I 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

(adamweinstein@ymail.com is my email if there are any solutions to this! Appreciate it fellas!)

Arif said...

Hello Tamada why you save in db isn't it ok to store then session.
is this use in latter use.

Anonymous said...

can't the Java to render the facebook News Feed. I have DB connection but is shows no Java.

Anonymous said...

where is the query that insert into users table?

how can we update without insert it first..

kabeen said...

1. can't download the scripts
2. why is it not possible in locahost?...i ve added to the facebook application settings , siteURL as http://localhost....won't that work??

dave said...

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)...

I 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,

Srinivas Tamada said...

@Dave

What was the exact problem in download script, let me know I will modify.

Srinivas Tamada said...

@Kabeen

Facebook app supporting live domains

Karen Johnson said...

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

Anonymous said...

can you please help me to solve my problem?

here 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: rioeduardo92@yahoo.com

thanks before :)

MarcTraining said...

Why cant we download the files? You only let us get facebook.php which we could get right from their site.

Fukkiit.com -er said...

Srinivas I'm trouble it's now allowing me to add facebook. It's just loading into the same home.php page.

andrew j talcott said...

As many others have pointed out, this code does not INSERT into the database, so, this code does nothing.

Anonymous said...

Great tutorial!!

swangsuresh said...

i need who to create app on facebook

Anonymous said...

$session = $facebook->getSession();
empty problem refresh null whats? $user_session

Anonymous said...

home?access_token= problem
?({
"error": {
"type": "OAuthException",
"message": "An unknown error has occurred."
}
});
friends?access_token= token true
so what home undefined

Anonymous said...

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'
again. please help

Anonymous said...

mysql_fetch_array() expects parameter 1 to be resource, boolean given

Anonymous said...

Please how do i get this: require("facebook.php");

Tom said...

How can this be made so the facebook login pops up and redirects back to the page.

Abhimanyu singh rathore said...

hi nice script i m really thankful to you
but 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 abhirathore2006@gmail.com

Anonymous said...

Hi.. where I can find this?

# We require the library
require("facebook.php");

Anonymous said...

Hi... I only get NULL as result of
$session = $facebook->getSession();

why?

Anonymous said...

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!

Yash said...

Hi Sri,
Since 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.

Danish said...

Yes Srinivas,
plz suggest how to fix this session thing. The $session is always NULL. Plz help.

Anonymous said...

Good!

Praveen said...

hi...In the fbaccess.php there is an error i find it..can u help me out...error message is
Parse error: syntax error, unexpected...it is frrom the exception handling ,,,,any one of you can help me out

Anonymous said...

How to solve this
"error": {
"message": "Invalid redirect_uri: Given URL is not allowed by the Application configuration.",
"type": "OAuthException"
}

LIZO said...

code having some error ... any way we can make it running

telugucinemalo said...

gr8 thanks

Drunk stories said...

Great to hear from you. I feel interesting to read your blog. Its really informative too..

Satish Bhutawale said...

how to access the likes and comments from a facebook webpage and store it in a database..!!!

vstar said...

shrinivas tamada....hey solve our query dear.... How to access the Likes and Comments from outside of facebook page and store in a database .......

Anonymous said...

Hey Srini,

Awesome tutorial..:)
But the thing is that it not returning session dude...
Please help me out..

Thanveer said...

This is my code.I have to store the uid,name and access token of the user into my database.

How 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

DiamondKing said...

{
"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
}
}

Anonymous said...

$facebook->getSession(); is returning nothing in fbaccess.php

Kunal Khaware said...

Same issue ...
$facebook->getSession(); is returning nothing in fbaccess.php

Kunal Khaware said...

Hey Srini,
Could you please see if there is an issue in your code since $facebook->getSession(); is returning empty

boris stievet said...

Use GetUser() instead

Dewayne Michael Carter, Jr. said...

doesnt insert anything to DB no tokens begin inserted into be DB

Anonymous said...

its not doing anything to DB no updates there no access token not userid no username

Anonymous said...

By default in database there is no value to update what can i update through the update query with inserting any row.

budy said...

Another nice tuts

Post a Comment