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.
3 | require_once "php-sdk/src/facebook.php" ; |
6 | "appId" => FACEBOOK_APP_ID, |
7 | "secret" => FACEBOOK_APP_SECRET); |
9 | $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.
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.
3 | "redirect_uri" => REDIRECT_URI, |
4 | "scope" => "email,read_stream,publish_stream,user_photos,user_videos" ); |
5 | 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:
2 | $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.
2 | $data = array ( "message" => "Hello World!" ); |
3 | $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.
2 | $fb ->setFileUploadSupport(true); |
4 | "name" => "a vacation photo" , |
5 | "image" => "@/home/hari/vacation/img42.jpg" ); |
6 | $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.
03 | require_once "php-sdk/src/facebook.php" ; |
06 | "appId" => FACEBOOK_APP_ID, |
07 | "secret" => FACEBOOK_APP_SECRET); |
09 | $fb = new Facebook( $config ); |
11 | $user = $fb ->getUser(); |
15 | <title>Hello Facebook</title> |
21 | "scope" => "read_stream,publish_stream,user_photos" , |
22 | "redirect_uri" => REDIRECT_URI); |
23 | echo '<a href="' . $fb ->getLoginUrl( $params ) . '">Login</a>' ; |
27 | <form action= "<?php echo $_SERVER[" PHP_SELF "];?>" method= "post" enctype= "multipart/form-data" > |
28 | <textarea name= "message" id= "message" rows= "2" cols= "40" ></textarea><br> |
29 | <input type= "file" name= "image" id= "image" ><br> |
30 | <input type= "submit" value= "Update" > |
34 | if ( $_SERVER [ "REQUEST_METHOD" ] == "POST" && ! empty ( $_POST [ "message" ])) { |
35 | if ( is_uploaded_file ( $_FILES [ "image" ][ "tmp_name" ])) { |
36 | $finfo = finfo_open(FILEINFO_MIME_TYPE); |
37 | $mime = finfo_file( $finfo , $_FILES [ "image" ][ "tmp_name" ]); |
38 | $allowed = array ( "image/gif" , "image/jpg" , "image/jpeg" , "image/png" ); |
40 | if (in_array( $mime , $allowed )) { |
42 | "name" => $_POST [ "message" ], |
43 | "image" => "@" . realpath ( $_FILES [ "image" ][ "tmp_name" ])); |
44 | $fb ->setFileUploadSupport(true); |
45 | $status = $fb ->api( "/me/photos" , "POST" , $data ); |
50 | $data = array ( "message" => $_POST [ "message" ]); |
51 | $status = $fb ->api( "/me/feed" , "POST" , $data ); |
55 | echo "<pre>" . print_r( $status , true) . "</pre>" ; |
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.
Source : http://phpmaster.com/integrating-with-facebook/