How to implement Facebook Connect on a PHP website

With 250 million users worldwide, Facebook can’t be ignored. If you have a website where users can log on to, Facebook Connect can help getting your usage numbers increased. Facebook Connect allows for an easy way for users to log on to your site.

A simple Facebook Connect button button will allow the user to log on to your site with their Facebook credentials. They don’t have to register, choose and remember a password, click on a confirm link, … The advantages seem to be clear.

Adding Facebook Connect to your website is not that hard, as a lot of information can be found at http://developers.facebook.com/connect.php. But there are some missing pieces to make it really easy if you have a website running PHP. So let me try to fill in the gaps.

The main steps can be found at http://wiki.developers.facebook.com/index.php/Connect/Setting_Up_Your_Site:

  1. Create an application with the Facebook Developer application. This will provide you with an Facebook Platform API key.
    Follow steps 1-9 and note your public API key and a secret code.
  2. Download the Facebook PHP Client Library from http://wiki.developers.facebook.com/index.php/PHP.
  3. Upload all files in the /php folder to a folder on your webserver:
    • facebookapi_php5_restlib.php, facebook.php, facebook_desktop.php
    • all files in the /php/jsonwrapper subfolder

To use the API in your php-pages, you need to create a new Facebook object with your public AND secret API key:

require_once("../functions/facebook.php");
$facebook = new Facebook('public_key','secret_code');
$fbid = $facebook->user;

$facebook->user is the facebook userid. If this is empty, the user has not yet logged in. You can get show a Facebook login button by using some XFBML-code:

if (!$fbid)
  { ?>
    <p>Log in with your facebook-account:
    <fb:login-button onlogin='window.location="redirect-page";'>
    </fb:login-button>
    </p>
   <? }

For this to work, you need to set up your site. Follow steps 1-5 for the XFBML code to work.

If the facebook userid is not empty, you can get information about the user with the users_getInfo method:

else
  {
    $user_details = $facebook->api_client->users_getInfo($fbid, 'first_name,
pic_square');
    if ( isset($user_details) )
      { ?>
	<p><? if ( $user_details[0]['pic_square'] != '' )
               { ?>
                 <img src="<?=$user_details[0]['pic_square']?>" />
            <? } ?>
           Hello <?=$user_details[0]['first_name']?>, you are logged on
via Facebook.</p>
           <p><a href="#"
onclick="FB.Connect.logoutAndRedirect('/connect/logged_out.php')">log out</a></p>
    <? }
  }

Experimenting with Adobe AIR and jQuery – Part 7

In Step 7 of my Top100-application, I wanted to be able to enter a number and press ENTER, to immediately go to that specific number in the list. This is very similar to the ability in PowerPoint to move to a specific slide by just typing the slide number and pressing ENTER in Slide Show mode.

That piece was pretty easy with jQuery:

var newnumber = ''; // string to store numbers typed on keyboard
$(document).keyup(function(e) {
  if ( (e.keyCode>=48) && (e.keyCode<=57) )
    {
    // numbers (0..9)
    newnumber = newnumber+(e.keyCode-48);
    }
switch ( e.keyCode ) {
 case 13: // ENTER
  // switch to newnumber (if newnumber is number <= 100)
  var n = parseInt(newnumber);
  if ( (n>0) && (n<=100) )
    {
    currentnumber = n;
    // same effect as down-key
    $("#mainp").hide("slide", { direction: "left" }, 1500, function(){
      colornumber = currentnumber % bgcolors.length;
      $("#mainp").css("background-color",bgcolors[colornumber]);
      $("#mainp").css("color",textcolors[colornumber]);
      $("#number").text(currentnumber);
      $("#artist").text(lijst.record[numbers[currentnumber]]['artist'].toUpperCase());
      $("#title").text(lijst.record[numbers[currentnumber]]['title'].toUpperCase());
      $("#mainp").show("slide", { direction: "right" }, 1500, function(){
        $("#number").effect("pulsate", { times:5 }, 1500);
        });
      });
    }
  newnumber = '';
  break;

This worked, but only when using the numbers at the top of the keyboard. From the Keyboard Events page on Javascript Madness I learned that the keyCodes for the numbers on the numeric keypad are different (well, in IE, FireFox, Safari and Chrome, not in Opera): pressing the 1 key at the top results in keyCode 49, pressing 1 on the numeric keypad results in 97. So I had to add another series of keyCodes (96..105).
Also, I noted that when I started with a 0, I did not get the result I expected. Typing 055 ENTER resulted in number 45 being shown. After looking at Converting Javascript strings to numbers at the Javascript FAQ website, I realized the 0 at the start makes Javascript interpret it as an octal. So I included some code for that as well:

if ( (e.keyCode>=48) && (e.keyCode<=57) )
    {
    // numbers (0..9)
    if ( !((e.keyCode==48) && (newnumber == '')) )
      // don't start with 0 --> will be interpreted as octal
      {
      newnumber = newnumber+(e.keyCode-48);
      }
    }
  else if ( (e.keyCode>=96) && (e.keyCode<=105) )
    {
    // numbers (0..9) on numeric keypad
    if ( !((e.keyCode==96) && (newnumber == '')) )
      // don't start with 0 --> will be interpreted as octal
      {
      newnumber = newnumber+(e.keyCode-96);
      }
    }

The final addition I made was support for the BACKSPACE key. If you accidentally typed the wrong number, pressing BACKSPACE would erase all input:

switch ( e.keyCode ) {
...
  case 8: // backspace
    // reset newnumber
    newnumber = '';
    break;

♦ Related files: step7.html

Experimenting with Adobe AIR and jQuery – Part 6

Until now, I had hard-coded the information about 3 songs in my Top100-application. It was time to make it dynamic, loading 100 songs from an XML-file.

The file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<top100>
<record>
  <number>1</number>
  <artist>Captain &amp; Tennille</artist>
  <title>Do That To Me One More Time</title>
</record>
<record>
  <number>2</number>
  <artist>Irene Cara</artist>
  <title>Fame</title>
</record>
... 

So I looked for solutions to read an xml-file with javascript. Sure enough, jQuery had a solution: the XML-to-JSON jQuery plugin makes it really easy to do this.

The code

var lijst = new Object();
$.get('top100.xml', function(xml){ 
  lijst = $.xml2json(xml);
  }); 

reads the file and puts the content into the JSON object lijst:

{record:[
  { number:1, artist:'Captain & Tennille', title:'Do That To Me One More Time' },
  { number:2, artist:'Irene Cara', title:'Fame' }, 
  ...
 ]}

As an example, I can access the title of the number 1 song by using

lijst.record[0].artist

(as javascript objects start numbering from 0). Obviously, this depends on the sequence of the songs in the xml-file, i.e. if the file would start with number 100 instead of 1, or if the sequence would be random, this would no longer work. As an xml-file by definition is not “sorted”, I needed to create an extra object to contain the object reference by song number:

var numbers = new Object();
var lijst = new Object(); 
$.get('top100.xml', function(xml){ 
  lijst = $.xml2json(xml);
  for ( var rec in lijst.record )
    {
    numbers[lijst.record[rec]['number']] = rec;
    }

This results in

numbers[1] --> 0, number[2] --> 1, ...

I could now use

list.record[numbers[1]]['artist']

to get the artist information for the number 1 song.

To be able to move up and down, I needed an extra javascript variable to keep track of the current song number that is shown on the screen, and initialize the screen with that number:

var currentnumber = 100;
$.get('top100.xml', function(xml){
  lijst = $.xml2json(xml);
  for ( var rec in lijst.record )
    {
    numbers[lijst.record[rec]['number']] = rec;
    }
  $("#number").text(currentnumber);
  $("#artist").text(lijst.record[numbers[currentnumber]]['artist'].toUpperCase());
  $("#title").text(lijst.record[numbers[currentnumber]]['title'].toUpperCase());  
});

I finally added 2 arrays to display various colors for the background and the text.


♦ Related files: step6.html