Facebook Graph API Connect with PHP and Jquery
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");
?>

70 comments:

  1. what is the output of this script

    ReplyDelete
  2. 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.

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

    ReplyDelete
  4. 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?

    ReplyDelete
  5. 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.

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

    ReplyDelete
  7. Users table

    facebook_id varchar(100)

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

    ReplyDelete
  8. 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

    ReplyDelete
  9. @Olinklist

    Facebook shutdown is fake news

    ReplyDelete
  10. I just wonder why you store access_token in database ?

    ReplyDelete
  11. 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..

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

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

    ReplyDelete
  14. 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.

    ReplyDelete
  15. 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

    ReplyDelete
  16. Will it works on localhost?

    ReplyDelete
  17. 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

    ReplyDelete
  18. 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

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

    ReplyDelete
  20. 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!)

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

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

    ReplyDelete
  23. where is the query that insert into users table?

    how can we update without insert it first..

    ReplyDelete
  24. 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??

    ReplyDelete
  25. 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,

    ReplyDelete
  26. @Dave

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

    ReplyDelete
  27. @Kabeen

    Facebook app supporting live domains

    ReplyDelete
  28. 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

    ReplyDelete
  29. 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 :)

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

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

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

    ReplyDelete
  33. Great tutorial!!

    ReplyDelete
  34. i need who to create app on facebook

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

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

    ReplyDelete
  37. 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

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

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

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

    ReplyDelete
  41. 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

    ReplyDelete
  42. Hi.. where I can find this?

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

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

    why?

    ReplyDelete
  44. 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!

    ReplyDelete
  45. 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.

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

    ReplyDelete
  47. 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

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

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

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

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

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

    ReplyDelete
  53. Hey Srini,

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

    ReplyDelete
  54. 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

    ReplyDelete
  55. {
    "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
    }
    }

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

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

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

    ReplyDelete
  59. doesnt insert anything to DB no tokens begin inserted into be DB

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

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

    ReplyDelete
  62. PLease update your code as facebook is using now graph api2.2 which have restrictions to share your information with others

    ReplyDelete