1. Code
  2. PHP

How to Authenticate Users With Facebook Connect

Scroll to top
Read Time: 9 mins

Lately, there's been quite a fuzz about lazy registration. It turns out that the less the user has to think, the higher the conversion rates are! What a thought! If everybody seems to have a Facebook profile, why not add a one-click user registration? I'll show you how to do that today.

Step 1. The Setup

MySQL Table

Let's begin by creating a database table.

Quite simple: we will be setting up a table for user information with id, username, first and last name, the URL to the user's picture, and registered date. Also, we're adding both an oauth_provider and oauth_uid fields, to distinguish between different third party open authentication protocols and their identifiers. For example, let's say that, next week, you decide that it's a good idea to also let Twitter users in. Easy; you just set another value to the oauthprovider, and avoid duplicating oauthuid values.

The Facebook App

Let's begin by creating a new application. Give it a name and agree to the terms and conditions. Next, grab both the API Key and Secret in the basic tab as shown below.

On the canvas tab, set both the Canvas URL and Post-Authorize Redirect URL to your localhost and path that the script will process -- something like Note the question mark at the end and the domain; both are required by Facebook. Simply set your hosts file to a valid domain name.

On the connect tab, set the Connect URL to the same value and set (or the one you are using) as the Base Domain.

Now save, download the client library, and unzip facebook.php in the srcdir to a new directory created in the root.

Step 2. The Callback

The authentication flow has three steps:

  1. The local script generates a URL asking the user for permission
  2. Facebook returns to the Canvas URL specified with a GET parameter
  3. The GET parameter authenticates the session

Let's make a quick test before registering and login.

Now, go to, and let's see what happens. If you are redirected to Facebook and requested for permission, we are on the right track.

However, there might be two issues. The first one: if you're redirected to Facebook, but it shows an error, there might be a missing value in the configuration. Go back to your application settings and check both the Connect and Canvas tabs and make sure the fields are ok as described above.

There might be another issue, where you see an error, like "Uncaught CurlException: 60: SSL certificate problem, verify that the CA cert is OK." This happens because of the CURL settings. You'll have to open facebook.php, find the makeRequest() method, and, inside the function, find this line:

Immediately following it, add:

I hate hacking libraries, but I haven't found another way. Well, let's continue with user registration. I've also added a try/catch statement, because, if there's an old session keys in the GET params in the URL, the script will die with a horrible error.

Step 3. Registration and Authentication

We'll next be working with MySQL. Please note that I will not implement a data sanitizer, since I want to keep the code as short and on task as possible. Please keep this in mind: always sanitize your data.

First, let's connect to the database.

Now, let's work on the $session conditional, in case we have a session.

Note that I'm querying the database, looking for facebook as a oauth_provider; it's generally a good idea, if you want to accept other OAuth providers (as twitter, Google Accounts, Open ID, etc.) and a oauth_uid, since it's the identifier the provider gives to its user accounts.

The oauth_provider field could potentially lead to bad performance if we leave it as a text field type. As such, the best option is setting it to an ENUM type.

We have now a $result var with the values queried from the database. Let's next add some sessions. Add this line at the beginning of your script.

After the empty($result) conditional, append the following:

As it makes little sense to authenticate a user who is already logged in, just below the session_start() line, add:

And in the scripts which require authentication, just add:

And if you want to display the username, access it as an array.

Step 4. Additional Methods

Facebook has a ton of connect features, but here are four that I've found to be the most useful.

Legacy Methods

I might be missing something, but the FQL seems more flexible and easy than the Graph API. Fortunately, Facebook still lets developers use it, altough with the new library, it has changed a bit.

If you want the user id, first name, last name, squared thumbnail for the user picture, the biggest user picture available, and his or her gender, you can use the users.getInfo method.

You can check the full list of fields available for Users.getInfo.

It is possible to achieve the same result, using FQL.

Here's the list of tables which can be accessed with FQL, as well as the fields available for the table users.

Extended Permissions

Facebook provides applications with some interaction with the user's data - just as long as it's authorized. With the old API, the authorization for additional permissions was exclusively available for the Javascript SDK (altough I'm not quite sure). With the new API, we can easily redirect the user to an authorization dialog in Facebook, and return to our site after the access is either granted or denied.

In the following example, we will be redirecting a user to authorize posts status updates, photos, videos and notes, the user's real email address, birthday and access to photos and videos.

Here's a full list of permissions. Note that you can specify both the url to direct to if the user accepts and the url to be redirected to if the user denies. The key for these array elements are next and cancel_url, respectively. Here's a quick example:

If not specified, the default is the requesting script's location.

Checking for Extended Permissions

Since the user can easily revoke permissions, the application should always check if a given permission is granted before using it, specially if it's about publishing something. We will have to use the legacy API, as it seems it's not fully implemented with the new one yet.

The ext_perm will only support the old list of available permissions.

Publishing to the Wall

Let's post something to the wall after verifying the user has the publish_stream permission.

Essentially, we are making an API call to /<user_id>/feed, using the POST method (second argument) and an array as a third argument for the data to be sent. In this case, this third argument supports message, link, picture, caption, name and description. Here's the code:

Here's how it is posted.

Some Additional Information you Should Know:

The user can easily revoke permissions with two clicks in his or her wall. You should heavily test what might happen if a user revoked one or more permissions that are vital for the proper functioning of your website, or even if the application is fully removed. This is important.

5. Conclusion

While Facebook's authentication capabilities are indeed useful, since so many people are on Facebook these days, using it as the only method of authentication in a site is not recommended. What about those who don't have Facebook accounts? Are they not allowed to access your application? Thanks for reading!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.