Authorizing on Your Web Site or in an iFrame Environment

In this section, I show you how to do a simple authentication, which uses OAuth 2.0 on the back end, in PHP. In Chapter 8, I also show you how to authenticate in JavaScript, so you have plenty of examples. Your language of preference probably operates similarly to the examples covered thus far and those I provide in this section.

Because your PHP library automatically handles things for you, you can authorize in both an iFrame Facebook.com environment and on your own Web site, all using the same code. Your PHP handles all the differences for you. (Hopefully by the time you read this, you will find no differences — currently Facebook is moving in this direction.)

Here's how you authorize in PHP:

  1. Initialize your application or Web site.

    You can do so with the following code:

    require 'facebook.php';
    
    // replace ". . ." with appropriate values
    $facebook = new Facebook(array(
     'appId' => '. . .',
     'secret' => '. . .',
     'cookie' => true,
    ));
  2. Determine whether a user is logged in.

    You do so with the getSession method of your $facebook object. The following code shows how this works:

    if ($facebook->getSession()) {
       // do stuff with the user – you've read their access token and the PHP
               libraries will automatically append it for you
    }
    else {
       // start the OAuth login process to authorize the user
    }
  3. If the user isn't logged in, give him the option to log in (or just redirect him).

    In this example, I print a Login button in HTML, but ...

Get Facebook® Application Development For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.