Integrating with Facebook Graph API

Tweet

Integrating with Facebook from PHP is easy with the help of Facebook’s PHP SDK and some HTTP libraries like Zend_Http_Client or PEAR HTTP_Request2. In this article I’ll show you how to get started using the Facebook PHP SDK. You’ll learn about the Facebook Graph API and create a Facebook application capable of updating your status message and uploading photos.

If you don’t have it already, you can clone or download the PHP SDK from GitHub. You’ll also need a verified Facebook account.

Registering your App on Facebook

You first need to register your application on Facebook. Go to developers.facebook.com/apps and click the Create New App button at the top of the page.

The dialog that opens asks you for the name and a namespace for your application. App Display Name is the name for your application that will be shown to the users. App Namespace is the namespace your application will use for Open Graph and Canvas Page.

After you register the application, you’ll be taken to the Basic Settings screen on which you need to specify how your app will integrate with Facebook:

  • Website – The website option is used for adding social functionality to your website.
  • App on Facebook – This Facebook app option embeds your application within a Facebook Canvas page. The code is hosted on your servers, but executes within the context of a Facebook page, similar to an IFrame.
  • Mobile Web – The mobile web option is similar to the Website integration option, although it’s intended for mobile sites.
  • Native iOS/Android App – The native options allow you to integrate Facebook data in your iOS and Android applications.
  • Page Tab – The tab option exposes your application as a Facebook page tab.

For the purposes of this article I’ll use the website integration option. My application will be a stand-alone website, and after authorization Facebook will redirect the user to a specified URL. Select the check mark next to the option and enter the URL for your application’s entry page. Then be sure to click the Save Changes button at the bottom of the page.

You should also make a note of the App ID and App Secret values at the top of the page since you will need these values to connect your application to Facebook.

Using the SDK

Functionality to connect and interact with Facebook is exposed through the Facebook object defined by the PHP SDK. The constructor accepts an array of parameters which contain information about your application, such as the App ID and App Secret that appear on your application’s Basic Settings page.

<?php 
session_start();
require_once "php-sdk/src/facebook.php"; 

$config = array(
    "appId" => FACEBOOK_APP_ID,
    "secret" => FACEBOOK_APP_SECRET);

$fb = new Facebook($config);

Authorization

The getUser() method is used to retrieve the user ID of a Facebook user. The information may or may not be available, depending on whether the user is logged in or not. If the method returns 0 then you know the user has not logged in.

<?php
$user = $fb->getUser();

The login link which serves the starting point for the OAuth authentication process with Facebook is obtained using the getLoginUrl() method. getLoginUrl() accepts an array of a parameters in which I’ve supplied redirect_uri and scope.

<?php
$params = array(
    "redirect_uri" => REDIRECT_URI,
    "scope" => "email,read_stream,publish_stream,user_photos,user_videos");
    echo '<a href="' . $fb->getLoginUrl($params) . '">Login</a>';

The redirect_url should be the same address you provided for Site URL when registering the application. The scope is a comma-separated list of requested permissions the application requires. Applications are allowed to access public profile information and other defaults as permitted by Facebook when the user is logged in, but if you want access to additional functionality (such as posting status messages) you must be authorized by the user to do so. The Facebook developers documentation has a list of available permissions. Here I’ve requested permission to to access the user’s email address, read and publishing status updates, post photos, and post videos.

Regardless if the user accepts the request and logs in to Facebook, or rejects the request, he will be redirected back to the redirect_uri and several values will be available as URL parameters. A rejection will include error, error_reason, and error_description parameters:

http://example.com/facebook/myapp.php?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request.

A successful authentication/authorization will append a code parameter, like so:

http://example.com/facebook/myapp.php?code=TOKEN_VALUE

The code is then used to request an Access Token:

https://graph.facebook.com/oauth/access_token?client_id=FACEBOOK_APP_ID&redirect_uri=FACEBOOK_REDIRECT_URI&client_secret=FACEBOOK_APP_SECRET&code=TOKEN_VALUE

As you’re using the SDK which handles all of this for you, I won’t go more into how OAuth works. If you’re interested in learning more read Dustin Runnell’s Understanding OAuth article and the SDK’s documentation on authentication. (Facebook uses OAuth v2 and Dustin’s article covers v1, but it will still give you a good idea of the role requests and credentials play in the process).

The Graph API

Once the user grants permission, you can read the user’s feed of status messages with a GET request:

https://graph.facebook.com/me/feed?access_token=ACESS_TOKEN

Alternatively, you can use the api() method which wraps a call to Facebook Graph API methods:

<?php
$data = $fb->api("/me/feed");

The api() method in this case can accept three arguments: the Graph API path for the request, the HTTP method for the request (defaults to GET), an an array of parameters specific to the Graph API method.

The Graph API provides an interface to access the members and relationships in Facebook’s social graph. Each member has a unique ID and can be accessed in a REST-like manner through resources starting with “https://graph.facebook.com”. For example, sending a GET request with your browser for:

https://graph.facebook.com/harikt

will return a JSON object with basic public information about me and my profile.

{
   "id": "596223095",
   "name": "Hari Kt",
   "first_name": "Hari",
   "last_name": "Kt",
   "link": "http://www.facebook.com/harikt",
   "username": "harikt",
   "gender": "male",
   "locale": "en_US"
}

Some requests require an Access Token. Requesting a feed of message updates is a privileged action, and so sending a GET request for:

https://graph.facebook.com/harikt/feed

will return a JSON object populated with information about an OAuthException error.

{
   "error": {
      "message": "An access token is required to request this resource.",
      "type": "OAuthException"
   }
}

The ID me is a convenient shorthand which refers to the current user.

To add an update to the user’s feed using the api() method, you would make a POST request to /me/feed and supply a message value.

<?php
$data = array("message" => "Hello World!");
$status = $fb->api("/me/feed", "POST", $data);

To upload a new photo you would make a POST request to /me/photos (or ALBUM_ID/photos to upload to a specific album) and supply an array with name and image arguments.

<?php
$fb->setFileUploadSupport(true); 
$data = array(
    "name" => "a vacation photo",
    "image" => "@/home/hari/vacation/img42.jpg");
$status = $fb->api("/me/photos", "POST", $data);

The SDK uses PHP’s cURL extension to post data, and calling setFileUploadSupport() with true will provide the data values to CURLOPT_POSTFIELDS as an array which in turn causes cURL to encode the data as “multipart/form-data”. Also cURL-related is the use of @ before the full path of the image to be posted. See the description for CURLOPT_POSTFIELDS in PHP’s documentation of curl_setopt() for more information.

To learn more about Facebook’s Graph API I recommend you to read the Graph API documentation and experiment with the Graph API Explorer which is quite a handy utility.

Your First Application

Let’s bring together everything you’ve learned now and write a very basic example of a Facebook application. It will prompt the user to log in and authorize the application, and then enable him to update his status message and upload a photo.

<?php 
session_start();
require_once "php-sdk/src/facebook.php"; 

$config = array(
    "appId" => FACEBOOK_APP_ID,
    "secret" => FACEBOOK_APP_SECRET);

$fb = new Facebook($config);

$user = $fb->getUser();
?>
<html> 
 <head> 
  <title>Hello Facebook</title> 
 </head> 
 <body>
<?php
if (!$user) { 
    $params = array(
        "scope" => "read_stream,publish_stream,user_photos",
        "redirect_uri" => REDIRECT_URI);
    echo '<a href="' . $fb->getLoginUrl($params) . '">Login</a>'; 
}
else { 
?>
  <form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" enctype="multipart/form-data">
   <textarea name="message" id="message" rows="2" cols="40"></textarea><br>
   <input type="file" name="image" id="image"><br>
   <input type="submit" value="Update"> 
  </form> 
<?php
    // process form submission
    if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST["message"])) {
        if (is_uploaded_file($_FILES["image"]["tmp_name"])) { 
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES["image"]["tmp_name"]);
            $allowed = array("image/gif", "image/jpg", "image/jpeg", "image/png");
            // upload image
            if (in_array($mime, $allowed)) { 
                $data = array(
                    "name" => $_POST["message"],
                    "image" => "@" . realpath($_FILES["image"]["tmp_name"]));
                $fb->setFileUploadSupport(true); 
                $status = $fb->api("/me/photos", "POST", $data);    
            }
        }
        else {
            // update status message
            $data = array("message" => $_POST["message"]);
            $status = $fb->api("/me/feed", "POST", $data); 
        }
    } 
    if (isset($status)) {
        echo "<pre>" . print_r($status, true) . "</pre>";
    } 
}
?>
 </body> 
</html>

The code presents a link to log in or out as appropriate depending on the return value of getUser(). Then, a simple HTML form is displayed which permits the user to enter a status message and possibly an image file. When the user submits the form, the code verifies the uploaded image if one is provided and posts it to Facebook, or performs just a status message update.

Summary

The code here is for demonstration purposes, and I’ve omitted a lot of filtering and security-related checks you’d want to perform when writing a real-world application. It does however highlight the main points presented in this article. The Facebook PHP SDK makes integrating with Facebook easy. It abstracts working with OAuth authentication and the Facebook Graph API.

Image via mkabakov / Shutterstock

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://jenson.in Jenson M John

    Valuable Info..:)

  • http://shameerc.com Shameer C

    Nice article dude. Thanks for writing it.

  • Krishna

    Wow ! ! !
    Interesting documentation Hari. I think it will be very helpful. I will try it and will let you know :)

  • http://www.jrworksts.com Jeremy

    This is an awesome article. I have a question though. If you are creating a custom facebook page that needs to post to that pages wall (from a custom input field) you don’t have to worry about authentication correct? How would you do something like that?

    • http://harikt.com/blog Hari K T

      Sorry I didn’t get exactly what you are looking for. Do you mean in a canvas app ?

  • Christoph

    Hi there,

    thanks for a great article. Could you explain how to store a users session in a cookie, in order to not log in each and every single time?

    Christoph

    • http://harikt.com/blog Hari K T

      Sorry may I didn’t get you exactly. Are you talking about something like “Enables your app to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.”
      Then have a look into the https://developers.facebook.com/docs/reference/api/permissions/ , you can use offline_access .

  • http://www.ondesign.gr/ gvre

    Awesome and very explanatory tutorial!
    Could you post some information about your development process (eg. testing your apps against new api, development of new version of your apps, etc).
    Thank you!

  • icon

    Hi.. Your tutorial is good… but when i did all the steps… and even after including the files and all.. when i run my application… ie., after clicking on Login link…. it is showing an error like this… “An error occurred with pix. Please try again later.” So what I have to do now?? Can you please tell me?

    • http://harikt.com/blog Hari K T

      Thank you icon,
      An error occurred doesn’t makes any sense to me. There will be more error codes thrown below . Something like
      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.

      So you want to make sure that the application id and the redirect uri etc are the same as your have registered in FB .

    • hakeem

      Make sure ur redirect_url is thesame with ur web or if you are running it on your local machine i.e 127.0.0.1 then you will have to change the redirect_url on your app setings to to 127.0.0.1. Hope this helps

  • http://heera.it Heera

    Awesome ! Though I’ve used Facebook’s graph api but I was not so clear about some of it’s process but now I’m clear and you have made it. So Thank you very so much.

  • http://www.rotibit.com/ Ake

    I’m not understand about App Namespace.
    What’s namespace.

  • codecowboy

    This code results in a redirect loop for me. I get redirected to the facebook login page and prompted to allow access after login but the code never reaches the else statement to make the graph API call. This is hosted locally on OSX. The redirect loop goes between the web site URL on localhost, which is set as the site URL in app settings and the oauth facebook URL

    Any ideas?

  • mary

    Hi, nice tutorial. can i know who like my facebook page? can i use this techniques to get the current user who liked my page? Thanks in advance.

  • vin

    How to get comments of a particular post in a website from where this is posted? Posting can be done with this website but we can’t collect responses again that user logged into our website?

  • Vaishakh

    Really helpful. I was searching for such an article to include in my website.Thanx a lot.

  • Vaishakh

    could u please post an example which gets some users info like “name” or something.

  • http://www.anil2u.info Anil Kumar Panigrahi

    Thanks Hari. But I want to publish a message to my facebook page using API. While fb-login I get the permission of publish_stream, manage_pages. Using below code I am able to post the message
    $facebook->api(“/[Page Id]/feed”, “post”, “[Message]“); But It is not displaying in the wall of page. If I login to that page ( Created page with different login details ) then only display those post message, ‘subscriber’ or ‘like’ user cannot get posted message. How can we rectify it so that I will integrate it into one of my website admin section.

  • varun

    do i need to own a domain inorder to test “login” plugin?

  • Joe

    So many intro to php facebook api scripts out there, and finally one that [expletive] works!!!

  • jay

    Thank you very much sir for explaining the details.

  • Madhu

    Thanks for this excellent article.

    I am able to post messages to the wall. But for some reason, It doesn’t post photos to wall. I have enabled publish_permission & user_photos permission for the apps. What could be the problem? Do I need to enable any other permission for uploading photos?

    Appreciate your help on this.

  • http://www.tycoonwar.com Business Game

    @ Hari K T
    i am having issue with this code. when i run it, it shows ‘Login’ text. i clicked it, it ask for facebook permissions. I allowed it. after that it redirects it back to page showing again ‘Login’ when i debug it, its showing user_id null.

  • Aniket Harne

    Nice info….thank you very much…just wanted to know (as I am new to this) how Logout url will work if I put the getLogoutUrl() code in href attribute of logout anchor of the website..? I mean I just want the possibility to destroy user’s session from my website but not on actual facebook website (which is open in other tab of the same browser)..?

  • http://www.specialone.gr giannis gourniezakis

    very nice tutorial…

  • http://www.raeesiqbal.tk AneesIqbal

    Sorry but your Tutorial is not working anymore.

  • programmer

    Hi am used above application it posts text to others wall fine but it does not posting photos when am try to upload the photos am getting error like this
    Fatal error: Call to undefined function finfo_file() in C:wampwwwmyphp.php on line 37 please solve waiting for ur reply

  • http://harikt.com/ Hari K T

    Your PHP version is less than 5.3, see http://www.php.net/manual/en/function.finfo-file.php either you need pecl extension installed for the version before it, or use something else.
    @AneesIqbal I am no longer testing this. Thanks and let me know what is getting wrong at the end.

  • programmer

    Hi
    Ok i will use above php 5.3 and and i have one doubt is it works only localhost or it works in live website also?