How to get email adress from Facebook PHP SDK? - php

Hi there i am currently working on Facebook login for my website.
For now i can display everything else like First name, Second name, ID of facebook member id but i can't not display the email.
Here is my php code:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'MYIDDDDDD',
'secret' => 'MYIDDDDDD',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email'));
}
$naitik = $facebook->api('/naitik');
$myid = $user_profile['id'];
$myemail = $user_profile['email'];
echo $user_profile['first_name'];
echo "Your id is - $myid<br>My email is = $myemail";
$_SESSION['first_name']=$user_profile['first_name'];
?>
If it's important my App is in Sandbox mode.
Where is my mistake in this code and why $myemail = $user_profile['email']; is show as blank?
Thanks in advance!

Did you first get the users permission to see his email?
https://developers.facebook.com/docs/reference/login/email-permissions/
if not, see this post Set permission for getting User's email ID from Facebook Login

Related

PHP Facebook SDK doesn't work and returns code

My PHP Facebook SDK is not working and always returns $user=0 Why?
It is my first time to deal with facebook sdk
my code:
require './facebook-php/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx'
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if($user) {
$logoutUrl = $facebook->getLogoutUrl(); echo 'there is a user';
} else {
$loginUrl = $facebook->getLoginUrl();
echo 'there is noo user <a href='.$loginUrl.'>login</a>';
}
below is the url return code :
http://localhost/e-commerce/testit.php?code=AQA8DckDMqNarptbCUIfAmn2tIyn1mjVBmHTjOMaQ4GqsFW_6vqemGW35TC07Kxq7kuB4QkKibHJ2-m9GntIx0biWEiR_FUuozsONvgc_tNmtGURpcm78DnIE26vT6hbjz10eZECuh-GLec9tGplhLrDNbLO-aX2Hv2Mu-8CQhAdiFQ6AYW3Nt09a8Rzahbn35Jz0cNyB_G7Ksjorq3iSs6Bpa6Tk0d7Vx0A0f1Mg77PgD6IuN_grjkNHDWmb_ywoqW48IqoxJUhnRmL3qi1G-CT7ft_f77rRr-VP-yQ-LTkdNja0rBzoFnFGccMuQ86u8tk7nfnx5qrSLBpHLEIBqQT&state=84ff9f36e8de53d13c96bcf7cb2da3b3#=
I have uploaded Facebook setting image
Facebook settings images

email is not saved in database from Facebook id in php

My email id is not stored in database. I want to store details of Facebook user in my database. Actually, I have login page in which, user can also login with Facebook but problem is that i get all details except email. I need store the email id also in database.Please help me.any help is appreciate.
here is my code...
<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}catch (FacebookApiException $e){
error_log($e);
$user = null;
}
if(!empty($user_profile )){
# User info ok? Let's print it (Here we will be adding the login and registering routines)
$username = $user_profile['name'];
$uid = $user_profile['id'];
echo $email = $user_profile['email'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['email'] = $email;
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: home.php");
}
}else{
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
}else{
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl(array( 'scope' => 'email'));
header("Location: " . $login_url);
}
It is just a suggestion.
Sometimes If user will not give permission access his email id in Facebook. at that time you will not get email id of that user.
So in that scenario you can store user email as 'userid#facebook.com'.
userid is also unique in facebook for every user. So you will get unique email id for every user.
Replace the below line :
$user_profile = $facebook->api('/me');
with the following code:
$user_profile = $facebook->api('/me?fields=id,name,first_name,last_name,gender,locale,timezone,email');

How to get user profile info using access token in php-sdk

I want to get user profile using access token that i have already generated, and if the access token is invalid it shoud display error. anyone can help to do this ? i want php code to handle this. i am waiting....
Since you already have the access token, the simplest and clean way would be-
$user_details = "https://graph.facebook.com/me?access_token=" .$access_token;
$response = file_get_contents($user_details);
$response = json_decode($response);
print_r($response);
First check if the user is logged in
$facebook = new Facebook(array(
'appId' => 'AppIDHere',
'secret' => 'AppSecretHere',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
If your access token is not null, fetch user data
<?php if ($user): ?>
Profile Picture: <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
User Id: <?php echo $user_profile['id'];?>
Name: <?php echo $user_profile['name'];?>
First Name: <?php echo $user_profile['first_name'];?>
Last Name: <?php echo $user_profile['last_name'];?>
Link: <?php echo $user_profile['link'];?>
Gender: <?php echo $user_profile['gender'];?>
Username: <?php echo $user_profile['username'];?>
<?php else: ?>
<strong>You are not Logged In.</strong>
<?php endif ?>
The user variables can be got from Facebook Graph API
If You want to get user_email and other info then you can use this code....
$facebook = new Facebook(array(
'appId' => 'AppIDHere',
'secret' => 'AppSecretHere',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me?fields=email,name,id,gender');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
I used facebook graph Api
$facebook = new Facebook(array('appId' => $fbconfig['appid'],'secret' =>
$fbconfig['secret'],'cookie' => true,));
$session = $facebook->getUser();
if($session)
{
try{
$uid = $session;
$fbme = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
// FQL : to fetch the email id
$fql = "SELECT email FROM user where uid='".$uid."'";
$response = $facebook->api(array('method' =>
'fql.query','query' =>$fql,));
$user_email = $response[0][email];
// Friend COunt.
$friend_res = $facebook->api('/me/friends');
$friend_count = count($friend_res[data]);
//likes
$likes = $facebook->api('/me/likes');
$fb_like = $likes[data];
// Getting more user personal data
$param = array(
'method' => 'users.getinfo',
'uids' => $uid,
'fields' => 'name,sex,pic,current_location,profile_url,email,birthday',
'callback'=> ''
);
$userInfo = $facebook->api($param);
}catch(FacebookApiException $e){
}
}

Login with facebook is not working properly

I am using facebook api for using login functionality of facebook on my website. But there is a problem with it, it does not redirected to my website after login. It redirects to facebook home page. I don't know why it happens. My code is below:
This file name is logign_facebook.php
<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
$facebook = new Facebook(array(
'app_id' => APP_ID,
'app_seceret' => APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if (!empty($user_profile )) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
$username = $user_profile['name'];
$uid = $user_profile['id'];
$email = $user_profile['email'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['email'] = $email;
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: home.php");
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl(array( 'scope' => 'email'));
header("Location: " . $login_url);
}
?>
Please help me to fix this issue.
Thanks
Facebook needs to know the URL to redirect back to when the user has logged in.
You can pass this through the the getLoginUrl() function in the PHP SDK as below:
$login_url = $facebook->getLoginUrl(array(
'redirect_uri' => 'http://yoururlhere.com/logign_facebook.php',
'scope' => array('email')
));
A full list of parameters for this function can be seen at https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl.
Another solution:
https://developers.facebook.com/apps/
Apps>>[app_name]>>basic
And scroll down to the "Website with Facebook Login"
Enter your desired URL in the textfield.

$facebook->api('/me') not giving the user data

require_once($_SERVER['DOCUMENT_ROOT'] . '/facebook-php-sdk/facebook.php');
$facebook = new Facebook(array(
'appId' => FB_MAIN_APP_API_ID,
'secret' => FB_MAIN_APP_SECRET
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Above is the code I'm using to get the Facebook details for my application. In my localhost this is working fine and it gives my Facebook email, user id. After I upload this in to live server this function is not working and it's not giving my Facebook details. I checked on the Facebook app id and it is the correct one.
I cannot figure out why it's not working in live site since it is working in my localhost. Please help me with this. Thank you.
I think problem is in your app which your are using on server. So try the same app which you are using for your localhost and in login and logout url instead of localhost use $_SERVER['HTTP_HOST'].
Example :
$session->fb_logout = $facebook->getLogoutUrl(array('next' => "http://" . $_SERVER['HTTP_HOST'] . "/path/to/logout"));
First check that what $user_profile = $facebook->api('/me'); showing. Just print_r the variable $user_profile.
Ex :
$user_profile = $facebook->api('/me');
print_r($user_profile);
exit;
if it showing blank then surely it will go in catch block. Then write following in catch block.
print_r($e);
exit;
For geting the user id, user need to grant permission
$user_id = $facebook->getUser();
echo $uid;
if($user_id){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
}
}else{
$login_url = $facebook->getLoginUrl();
echo("<br>login url=".$login_url);
};
After the user grant permission check the login_url, you may access user id.
Try this
Have you checked you have the correct URL in the configuration of your app in Facebook?
I have this piece of code to my FB apps and work properly, could you try it?
$session = $this->facebook->getUser();
if ($session) {
$logoutUrl = $this->facebook->getLogoutUrl();
try {
$data['uid'] = $this->facebook->getUser();
$me = $this->facebook->api($session);
$data['me'] = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$loginUrl = $this->facebook->getLoginUrl(
array(
'scope' => 'publish_stream, user_about_me, email',
'redirect_uri' => 'YOUR URL',
'canvas' => 1,
'fbconnect' => 0,
'display' => 'page',
));
}
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
$this->load->view('MY VIEW', $data);

Categories