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





very nice article. Clear one….thanks buddy
Thanks a lot Saran.
Cool i will start playing with this coz i need a user section with fb , gmail & yahoo users, regards Ranji
Hello
I really found this article very useful. I want to use the same code for one of my application. I have EasyPHP server and store all the files in www folder of it. When I try to redirect the pages using the command “http://127.0.0.1/facebook-api/”, I am not directed to the required page whereas if I use your default settings “http://jobyj.in/facebook-api/”, it redirects correctly. Can you please help me out with this issue?? I have been banging my head since days but arrived at no result.
Thank you
Hello,
Thanks for this article. I appreciate your contribution but I have a question about a problem I am facing. I have loaded the files onto my server and everything is working as intended except whenever I log out from the “Logout” button, it will refresh the page (correctly logging me out from Facebook) but after the refresh, the nav bar still shows my Facebook profile photo and name, along with the log out text. It appears that I’m still logged in but in the actual fact, I logged out according to facebook.com
I tried the demo on your site and your’s is working as intended but mine is not. Hope you can help on this. Thanks!
regards.
same problem as above, it doesn’t logout
Hi Joby,
Thanks for this awesome tutorial. I just have one doubt suppose I want to upload the photo to my PAGE photo rather to my Profile photo how can I do it. Please help me regarding this
hello, i want to create an app, that allow de user to select a folder on the hard disk, this folder has 10 or 12 subfolders each one with 20 photos,the appa must create an album for each subfolder and upload all the subfolder pics to the album, and make the same procceso with all the subfolders, is this possible with php?? i appreciate your help.