Site icon Web Niraj

Facebook API: Using the Facebook PHP SDK v4.1.x

As version v4.1 of the Facebook PHP SDK nears release, I though this would be a good time to explain how the new version works. This is the first major update to the SDK since it was released in May 2014, and one that has been mostly lead by the open-source community.

It’s worth noting that v4.1 of the SDK is quite different to v4.0.x, and anyone upgrading to the new version should be aware that it will break your application until you update your integration. Unfortunately, there is no easy way to migrate to the new version.

Warning: Migrating from v4.0.x to v4.1 will break your application.

Getting Started

Assuming you’re not using composer, here is how you include the SDK files in your code:

See the gist on github.

If you’re using composer, you’ll only need to include the session_start() part on line 10 (again, assuming you haven’t started the session elsewhere).

Note: At time of writing, I’m waiting for a pull request to be merged into the SDK to fix an issue with the autoload script. If this has not been merged, you will see a Fatal Error in the next step. Please see the diff of the pull request to see how to fix the issue.

Setting up your Application

You can then initialize the SDK using your API Key and API Secret from Facebook. In addition, you can (optionally) set the default HTTP Client (curl) and Persistent Data (PHP sessions) handlers.

See the gist on github.

Login and Make API Call

The next step is to log the user into your application and make a simple GET API call. This is a bulk of the code, as we need to check if the user has already been authenticated and then make the API call.

See the gist on github.

Detailed Code Explanation

Complete Code

POST Example

You can use the post() method to make POST call to the API. For example, the below code demonstrates how to publish to the user’s timeline (provided that the publish_actions permission has been granted):

See the gist on github.

Exit mobile version