Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code explanation for fb_php_sdk_4.1c.php

Line 4: We start by using the RedirectLoginHelper (you may be familiar with this from v4.0.x of the SDK). This is needed to generate the login / logout URLs and retrieve the Access Token from Facebook.

Lines 7-20: We check to see if the code has already been provided by Facebook after a login redirect. If we have one, we attempt to get the access_token using the helper (line 12), and then store this in the session (line 15).

Line 23: If we already have an access_token saved in the session we retrieve it here. The access_token saved on line 15 is also retrieved here. If the token does not exist, the $access_token variable will be null.

Line 26: We check if we have an access_token, and then make sure it hasn't expired.

Line 29: This is a function to set the default access_token for the user, so that all subsequent API calls use that token. If you don't want to set the default token, you can also pass it to requests manually.

Lines 31-39: This is were we make our GET request to get the user's profile information. If the request fails, we'll get an exception and stop the script. If you want to manually pass the access_token in the request, add it as the second parameter. e.g.

$response = $fb->get( '/me', $access_token );

You can acheve POST requests as follows (note that the second parameter is now an array of parameters to post):

$response = $fb->post( '/me/feed', [
    'message' => 'My first post using the Facebook PHP SDK v4.1'
  ], $access_token );

Lines 41-44: If the request is successful, we get the response and display the name (line 42) and the full response (line 44) here.

Line 46: This line gets the logout URL and displays a link to the user. The logout.php page should clear the PHP session or delete the persistent data you've set after logging the user in.

Line 50: This is where we present the login link to the user. The first parameter of the getLoginUrl() function is where the user should be redirected after logging in to your application. The second parameter is optional and should be an array of permissions you want to request. My example only asks for the email permission. The login link is only presented to the user if we don't have an access_token.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.