Facebook PHP SDK how to get user email from Facebook JavaScript SDK 2014

20,203

Solution 1

GraphUser inherits from GraphObject so you should be able to use the generic method to grab a field:

$user_profile->getProperty("email");

Solution 2

// Facebook SDK v5 for PHP
// https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript/5.0.0

session_start();

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

$helper = $fb->getJavaScriptHelper();
$accessToken = $helper->getAccessToken();

$fb->setDefaultAccessToken((string) $accessToken);

$response = $fb->get('/me?locale=en_US&fields=name,email');
$userNode = $response->getGraphUser();

var_dump(
    $userNode->getField('email'), $userNode['email']
);

Solution 3

Change login url to

$loginUrl = $facebook->getLoginUrl(array(
   'scope' => 'email'
 ));

you can also add additional permissions like

$loginUrl = $facebook->getLoginUrl(array(
   'scope' => 'email, user_activities '
 ));

Request permissions before you get login url.

check permissions with facebook login here

So you can get user email

 $user_profile['email'];

and username by

$user_profile['username'];

Solution 4

Change FacebookRequest() Parameter as below. change getLoginUrl() parameter as below

   $request = new FacebookRequest( $session, 'GET', '/me?locale=en_US&fields=name,email' );
 $loginUrl = $helper->getLoginUrl( array(
    'scope' => 'email'
  ));
Share:
20,203
user3753569
Author by

user3753569

Updated on February 17, 2020

Comments

  • user3753569
    user3753569 about 4 years

    I am using both Facebook PHP(4.0) and JS(2.0) SDK together. I can grab the user profile data with PHP but not the user's email. The user's email is available with the Javascript SDK, but I need it in PHP.

    I was using:

    $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); 
    

    This works but the class GraphUser does not have a function to grab the user's email in 4.0.

    Any ideas how I can grab user's email with Facebook PHP SDK version 4.0 ?

  • Flummiboy
    Flummiboy over 9 years
    this only works when $helper = new \Facebook\FacebookRedirectLoginHelper('your Url'); $helper->getLoginUrl(array('scope' => 'email')); is called when getting the LoginURL.
  • Zippy
    Zippy about 8 years
    Could you expand your answer by providing more info? Why should OP use this code?
  • besimple
    besimple about 8 years
    This is the only answer that worked for me. But I didn't call FacebookRequest before getLoginUrl but in combination with getGraphUser()