I want to access email id of the user, for that i tried below code, I checked many sites for this purpose. I found these ways to access user’s email id. But none of them seems to work. Please help me to solve this problem.
Thanks in advance.
<?php
session_start();
require_once 'autoload.php';
use FacebookFacebookSession;
use FacebookFacebookRedirectLoginHelper;
use FacebookFacebookRequest;
use FacebookFacebookResponse;
use FacebookFacebookSDKException;
use FacebookFacebookRequestException;
use FacebookFacebookAuthorizationException;
use FacebookGraphObject;
use FacebookEntitiesAccessToken;
use FacebookHttpClientsFacebookCurlHttpClient;
use FacebookHttpClientsFacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication('MY_app_id', 'my_app_secret');
$helper = new FacebookRedirectLoginHelper('http://prov.resolv.com/provision_sid/Facebook_2/fbconfig.php');
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
} catch (Exception $ex) {
}
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
echo $femail = $graphObject->getProperty('email');
die();
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
/* ---- header location after session ---- */
header("Location: index.php");
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: " . $loginUrl);
}
?>
I tried multiple option to request email id
1> $request = new FacebookRequest($session, 'GET', '/me?fields=name,email');
2> $request = new FacebookRequest($session, 'GET', '/me',['fields' => 'id,name,email,address,first_name,last_name']);
By above request too, I’m not able to get email id of the user.
Is there any other way to request email id of the user.
2
Answers
You need to ask for the
email
permission, by usingscope
in the login URL.SDK version 5:
SDK version 4:
Don’t forget to also request the email field:
Note: If the user does not agree to share email with your app you will not get it.
As per Facebook Policy, if User has kept Email as a Private then there is no way to get that else you can have it using following line.
$helper->getLoginUrl($redirectUrl, array('scope' => 'email'));