Facebook Authentication Using PHP SDK

0
SHARES

For most of the applications dealing with facebook API, first step will be authentication. Facebook Authentication is not required to access public information, but it is needed to access private information and other write permissions from user. Facebook developer site documents about authentication in this page. This page explains each step of authentication and how it is done at the very low level. For PHP developers, they don’t have to go behind the low level page redirection and access token check. Facebook provides SDK for PHP and it encapsulates all process in an easy to use manner.

Today we will discuss how to use facebook PHP SDK as a start for various other future tutorials. In this tutorial we are going to build a template which performs facebook authentication using PHP SDK. One of the main advantage in using PHP SDK for authentication is that, it is done on server side. Therefore it will not break in non javascript supporting browsers. Authentication can be done using javascript SDK also. But the process flow is different.

Facebook Authentication

You might have seen this design else where, because it is designed using the popular twitter bootstrap library. Now I have split the contents to different files for scalability. Here is the current folder structure. It may change a little bit in the future. So always download the latest version before executing the code.

Facebook Folder Structure

Now above screenshot is taken from Netbeans IDE. There the 3 files under php-sdk folder which are part of official facebook php sdk. We need to require facebook.php in our pages to use the SDK. You will get these files once you download the files from github. bootstrap folder contains the files needed for UI. You can see other files like config.php, footer.php, header.php and sidebar.php. These files form the main part of our template.

config.php
As the name suggest, I added this file to set all needed configuration. This will be required at the very beginning of header file so that all configuration is applicable to entire project. Users who download this project need to change only the config.php to run the project.

define('APP_ID', 'YOUR_APP_ID');
define('APP_SECRET', 'YOUR_APP_SECRET');
define('REDIRECT_URI', 'YOUR_REDIRECT_URL');//path till root folder ending with /

App Id and App secret is obtained when you register a new facebook application.

footer.php

It contains closing tags. In future if we need to add any footer script tags or analytics code we can add that here.

sidebar.php

This file is actually not required for you. I have placed this file to display any common information, ads etc. If you see require ‘sidebar.php’ anywhere just ignore it.

header.php

I took this file at last because it needs a detail explanation. It contains the core code for facebook authentication. Here is the php code added before starting html tag.

require 'config.php';

//Including facebook php sdk file
require 'php-sdk/facebook.php';

//Creating our application instance
$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET
        ));

//Get User ID
$user = $facebook->getUser();

if ($user) {
    try {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
    }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
    $logoutUrl = $facebook->getLogoutUrl($params = array('next' => REDIRECT_URI));
} else {
    $loginUrl = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI));
}

First 2 lines require the code from config and facebook sdk file. A new facebook object is created using the app id and app secret. We then try to fetch the current user id using getUser() function. If the user is not logged in getUser() returns null, else $user variable gets the userid.

Our aim is to display the user’s profile image and name if user is logged in to our application. Also we need to append a logout link to our app. If the user is not logged in, we will display a login button. For this purpose, we need to fetch user details if the user is logged in. This is done by $facebook->api(‘/me’); Here we are executing facebook graph api (/me) using facebook php sdk function api().

Facebook PHP SDK provides login url and logout url using getLogoutUrl() and getLoginUrl(). These functions accepts certain parameters which can change the redirect uri or scope of our application. In detail we will discuss that later.

Next you can find basic html lines in header.php which are toggled based on user’s login status.

index.php

This is the home page of our application. You can see how we constructed a complete page by requiring different files. We use title variable to give unique and meaningful title to all pages. path variable is placed to adjust the relative path to dependent files.

<?php
$title='Facebook API';
$path='';
?>
<?php include_once 'includes/header.php'; ?>
<div class="row">
    <div class="span12">
        <div class="hero-unit">
            <h1>Play With Facebook API</h1>
            <p>Demos to know the real power facebook api. Official facebook PHP and Javascript SDK are used for the demos.</p>
            <p>
                <a class="btn btn-primary btn-large" target="_blank" href="https://developers.facebook.com/">
                    Learn more
                </a>
            </p>
        </div>
    </div>
</div>
<?php include_once 'includes/footer.php'; ?>

Further enhancements will be done in the future tutorials. So get the latest code always.

Tags:

About Joby Joseph

Author of jobyj.in. I do a lot of research on web, APIs and social networks. Codes are mainly tried on PHP, jQuery, MySQL. Please support this blog by your facebook likes, twitter follow and RSS Subscribtion. Read more Google+