Basic File Structure of a Facebook App

The Facebook SDK for PHP Development Environment has been set up in previous post. As mentioned before, the example.php in the example folder is the best file to get started and learned. It’s time to see how to write PHP codes to connect with the Facebook servers.

Hosting Server and Development Files Preparation

1. Assume all developing files were saved in the following directory of hosting account:

2. The Facebook App will be saved in the Page Tab directory:

Therefore the Page Tab URL may be something like, whatever what filename you like:

Basic File Structure of a Facebook App

When a Facebook App require to connect with Facebook servers, the basic file structure should be something like below:


// We need to use the facebook.php file
 require 'fb/facebook.php';

// Created a new instance of our Facebook application
// pass app_Id and secret_key arguments as array to the constructor
$facebook = new Facebook(array(
  'appId'  => 'xxxxxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',

// Try to get the App User ID with getUser() function
 // This can check if a user session still valid or exist
 $user = $facebook->getUser();

// If $user id is not null, the user is logged into Facebook.
// But we need to check if the access token or session is valid.
// This can be done by calling to the Facebook Graph API, ie.
// An access token is invalid if the user logged out Facebook.
if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    $user = null;

// Continue the process or ask user to login,
//  depend on current user status.
if ($user) {
  // User logged in and has a valid access token or session.
  // do something or just leave it blank here...
} else {
  // invalid access token or session!
  // Authentication is required before accessing the Facebook App
  // Redirect user to a predefned authorization URL with the getLoginUrl() function
  $loginUrl = $facebook->getLoginUrl();


<title>My Facebook App</title>
  --- Contents of App here ---
  --- Contents of App here ---

As you can see, the file structure of a Facebook App that requires to connect with Facebook servers is not too complicated. Basically, the upper part is the user authentication and App authentication and authorization process. This is handled automatically by calling the Facebook class of the facebook.php file.  If the process go smoothly, the contents of the App, i.e. lower part of the file, will be displayed on the screen.

With the file structure, we can start developing App with the Facebook SDK for PHP easily.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>