Facebook Graph API, how to get users email?

To get the email of a user through the Facebook Graph API, you will need to:

  1. Have the user grant your app permission to access their email address. You can do this by using the email permission in your Facebook Login flow.

  2. Make a request to the Graph API to get the user's email address. You can do this by making a GET request to the /me endpoint and specifying the fields parameter with the value email.

Watch a course Learn object oriented PHP

Here is an example of how to do this in PHP:

<?php

$fb = new Facebook\Facebook([
    'app_id' => '{app-id}',
    'app_secret' => '{app-secret}',
    'default_graph_version' => 'v3.2',
]);

try {
    // Get the Facebook\GraphNodes\GraphUser object for the current user.
    // If you provided a 'default_access_token', the '{access-token}' is optional.
    $response = $fb->get('/me?fields=email', '{access-token}');
} catch (Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit();
}

$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();

// Print the email
echo 'Email: ' . $me->getEmail();

Note that this will only work if the user has granted your app the email permission and if the user's privacy settings allow your app to access their email address.