Facebook Connect with PHP SDK v4

Since my last post about Facebook connect back in 2012, Facebook still remains the top user registration source, well at-least in my imagination! And recently they have released PHP SDK version 4 with significant changes. So, today we are going to talk about it a bit and try and create a working Facebook Sign-Up page using their SDK v4. The Facebook SDK 4 version requires PHP 5.4 or greater, so if you are still on prior PHP versions, you might face problems with this SDK, this is mostly because of new Autoloader in PHP Library utilized by all PHP packages these days. So either you have to upgrade your PHP or use earlier SDK version for time being.

Connect to Facebook

Despite all the changes in the SDK, the process of implementation is still same and easy. You can download Facebook SDK 4.0 here, extract the package anywhere within your project folder, and include autoload.php in your project, take a look at a working example below :
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
<?php session_start(); //Session should be active $app_id = '453598374'; //Facebook App ID $app_secret = '934729857443983230943'; //Facebook App Secret $required_scope = 'public_profile, publish_actions, email'; //Permissions required $redirect_url = 'http://localhost/facebook-connect/'; //FB redirects to this page with a code //include autoload.php from SDK folder, just point to the file like this: require_once __DIR__ . "/facebook-php-sdk-v4-4.0-dev/autoload.php"; //import required class to the current scope use Facebook\FacebookSession; use Facebook\FacebookRequest; use Facebook\GraphUser; use Facebook\FacebookRedirectLoginHelper; FacebookSession::setDefaultApplication($app_id , $app_secret); $helper = new FacebookRedirectLoginHelper($redirect_url); //try to get current user session try { $session = $helper->getSessionFromRedirect(); } catch(FacebookRequestException $ex) { die(" Error : " . $ex->getMessage()); } catch(\Exception $ex) { die(" Error : " . $ex->getMessage()); } if ($session){ //if we have the FB session $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); //do stuff below, save user info to database etc. echo '<pre>'; print_r($user_profile); //Or just print all user details echo '</pre>'; }else{ //display login url $login_url = $helper->getLoginUrl( array( 'scope' => $required_scope ) ); echo '<a href="'.$login_url.'">Login with Facebook</a>'; }
This code basically connects to Facebook using their PHP SDK 4, and prints available details about the user on the browser. It asks for three user permissions: public_profile, publish_actions and email. You can guess what first one is, the second one publish_actions permission is required to publish texts or upload images on user wall, but you can remove it if not required by your application, third one is email permission which is required by most site. More info about user permissions can be found here.

Fetch User Details

Once the user details are available in $user_profile variable, you should know what to do next with that information. But the user data is enclosed in a protected GraphUser object, and if you try to access it usual way, you will encounter Cannot access protected property Facebook\GraphUser error. Here's a sample of GraphUser object for the current user.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
Facebook\GraphUser Object ( [backingData:protected] => Array ( [id] => 102417138XXXX [birthday] => 03/04/1990 [first_name] => Fred [email] => [email protected] [gender] => male [last_name] => TestMan [link] => http://www.facebook.com/102417138XXXX [location] => stdClass Object ( [id] => 102417138XXXX [name] => Middle Earth, Maryland ) [locale] => en_US [name] => Fred TestMan [timezone] => 5.0 [updated_time] => 2013-01-26T20:22:46+0000 [verified] => 1 ) )
To access this data, you can use getProperty() method and selecting the desired key, for example :
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
if ($session){ //if we have the FB session $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); echo $user_profile->getProperty('id'); echo $user_profile->getProperty('name'); echo $user_profile->getProperty('first_name'); echo $user_profile->getProperty('last_name'); }
The data you can access depends on the permissions a user has granted to your app along with the data a user has chosen to share with apps. If user does not share info such as email, it will come-out empty, so make sure to check any empty values before deploying. The most commonly used terms such as ID, name, first_name etc. can also be accessed directly like so:
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
if ($session){ //if we have the FB session $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); echo $user_profile->getId(); echo $user_profile->getName(); echo $user_profile->getFirstName(); echo $user_profile->getMiddleName(); echo $user_profile->getLastName(); echo $user_profile->getLink(); echo $user_profile->getBirthday(); echo $user_profile->getLocation(); }
If you want to convert these objects and access them as associative array, without protected property error, just add asArray() method. Something like this:
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
if ($session){ //if we have the FB session $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className())->asArray(); echo $user_profile["id"]; echo $user_profile["name"]; echo $user_profile["first_name"]; echo $user_profile["last_name"]; }

Upload an image on User Wall

You don't always want to get user data from Facebook, sometimes you also want to post pictures on user wall. Once you acquire the user session, this posting image is pretty easy, but you must have requested the publish_actions permission when logging in the user for this to work.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
if ($session){ //if we have the FB session $image = "/home/images/image_name.jpg"; $post_data = array('source' => '@'.$image, 'message' => 'This is test Message'); $response = (new FacebookRequest( $session, 'POST', '/me/photos', $post_data ))->execute()->getGraphObject(); }

Post link on user Wall

Posting link work similar way, publish_actions scope is required here too.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
if ($session){ //if we have the FB session $post_data = array( 'link' => 'www.example.com', 'message' => 'This is test Message' ); $response = (new FacebookRequest( $session, 'POST', '/me/feed', $post_data ))->execute()->getGraphObject(); }

Check Granted Permission

Sometimes you want to check particular permission before performing a task. For example before posting an image you might want to check whether a user has granted "publish_action" permission, because without this permission your application will run into nasty error. So, in that case you can use something like this:
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
if ($session){ //if we have the FB session $user_permissions = (new FacebookRequest($session, 'GET', '/me/permissions'))->execute()->getGraphObject(GraphUser::className())->asArray(); //check publish stream permission $found_permission = false; foreach($user_permissions as $key => $val){ if($val->permission == 'publish_actions'){ $found_permission = true; } } if($found_permission){ //do your stuff } }
Facebook graph has an endpoint "GET/{user-id}/permissions" to retrieve a list of granted permissions from user as JSON string, we can just loop through the list to check whether user has granted the permission we need.

Conclusion

That's it! For the sake of my old post, I've tried to cover most common aspects about the new Facebook PHP SDK v4, I hope this article could shed some light, even though their online documentation is fairly elaborated. Don't forget to checkout the Demo and downloadable file, which already contains Facebook SDK v4 package. All the best!Download Demo
New question is currently disabled!