I need help how can I convert this code into SDKv4. Cause this code is not working already and giving me redirect loop or something about looping of redirects.
<?php
require '../config.php';
require 'lib/facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => $appID,
'secret' => $appSecret,
));
//get the user facebook id
$user = $facebook->getUser();
if($user){
try{
//get the facebook user profile data
$getUserInfo = $facebook->api('/me');
$params = array('next' => $base_url.'logout.php');
//logout url
$logout =$facebook->getLogoutUrl($params);
}catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}
if(!empty($user)){
//login url
$userInfo = $getUserInfo;
$_SESSION['ses_id'] = md5(microtime());
$buid = $userInfo['id'];
$user = mysql_query("SELECT * FROM `scgfx_user_accounts` WHERE `fbid`='".$buid."'");
if(mysql_num_rows($user)>0) {
$userdata = mysql_fetch_assoc($user);
if($userdata['last_request_time']<=(time()-10800)) {
mysql_query("INSERT INTO `scgfx_chats` VALUES('','Welcome back to ".GLOBAL_NAME." <b>".$userdata['fbname']."</b>','0','global','".time()."')");
}
mysql_query("UPDATE `scgfx_user_accounts` SET
`gender` = '".$userInfo['gender']."',
`ses_id` = '".$_SESSION['ses_id']."',
`active` = '1',
`sign_time` = CURRENT_TIMESTAMP,
`last_request_time` = '".time()."',
`ip_address` = '".$_SERVER['REMOTE_ADDR']."' WHERE `fbid`='".$userInfo['id']."'");
} else {
mysql_query("INSERT INTO `scgfx_user_accounts` VALUES('',
'".$userInfo['id']."',
'".$userInfo['name']."',
'".$userInfo['gender']."',
'0',
'".$_SESSION['ses_id']."',
'1',
CURRENT_TIMESTAMP,
'".time()."',
'".$_SERVER['REMOTE_ADDR']."','0','0')");
mysql_query("INSERT INTO `scgfx_chats` VALUES('','We have a new member :) Welcome to ".GLOBAL_NAME." <b>".$userInfo['name']."</b>!<br/>Enjoy your stay!','0','global','".time()."')");
}
if(isset($_SESSION['ses_id'])) {
$getUserInfo = mysql_query("SELECT * FROM `scgfx_user_accounts` WHERE `ses_id`='".$_SESSION['ses_id']."'");
if(mysql_num_rows($getUserInfo)>0) {
while($data=mysql_fetch_assoc($getUserInfo)) {
$_SESSION['fbid'] = $data['fbid'];
$_SESSION['name'] = $data['fbname'];
$_SESSION['gender'] = $data['gender'];
$_SESSION['acctype'] = $data['acctype'];
$_SESSION['points'] = $data['points'];
}
} else {
die("Invalid Session ID");
}
?>
<script>
window.close();
window.opener.location.reload();
</script>
<?php
}
}
else {
$loginurl = $facebook->getLoginUrl(array(
'scope' => 'email,read_stream,offline_access,publish_stream,user_status,user_photos',
'display'=>'popup'
));
header('Location: '.$loginurl);
}
?>
<!-- after authentication close the popup -->
I think this is the only way I can get this code working.
I would try something like this:
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;
session_start();
FacebookSession::setDefaultApplication('app-id','app-secret');
$helper = new FacebookRedirectLoginHelper('this-same-url');
$session = $helper->getSessionFromRedirect();
if($session){
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
echo 'Token: ' . $session->getToken() . '<br/>';
} else {
// Create here your login button
$loginUrl = $helper->getLoginURL(array('public_profile,'));
echo("Login URL:");
echo($loginUrl);
}
Please note that this is a rough sketch and you should never echo the user token. For a more detailed explanation, please read https://developers.facebook.com/docs/php/gettingstarted/4.0.0
Related
I'm trying to build a website with a Facebook login button but when you click on the login button it brings you to my login.php page which is just empty. From what I can tell the getLoginUrl is just empty. Here is my code:
FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);
$helper = new FacebookRedirectLoginHelper(FB_REDIRECT_URI);
if(isset($_GET['type']) && $_GET['type'] == 'facebook' ){
$fb_url = $helper->getLoginUrl(array('email'));
header('Location: ' . $fb_url);
}
$session = $helper->getSessionFromRedirect();
if(isset($_SESSION['token'])){
$session = new FacebookSession($_SESSION['token']);
try{
$session->validate(FB_APP_ID, FB_APP_SECRET);
}catch(FacebookAuthorizationException $e){
echo $e->getMessage();
}
}
$data = array();
if(isset($session)){
$_SESSION['token'] = $session->getToken();
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::className());
$data = $graph->asArray();
$id = $graph->getId();
$image = "https://graph.facebook.com/".$id."/picture?width=100";
$data['image'] = $image;
if($user_obj->fb_login($data)){header('Location: home.php');}
else{header('Location: index.php');}
}
Does anyone know what could be wrong with my code?
<?php
session_start();
require 'config.php';
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => $appID,
'secret' => $appSecret,
));
$user = $facebook->getUser();
if($user){
try{
$user_profile = $facebook->api('/me');
$params = array('next' => 'website' );
$logout =$facebook->getLogoutUrl($params);
$_SESSION['User']=$user_profile;
$college = null;
foreach ($user_profile['education'] as $education) {
if ($education['type'] == "College") { //store the name data
$college = $education;
break;
}
}
if(empty($college)) {
echo "College information was not found!";
} else {
// var_dump($college);
echo "name" . json_encode($college);
}
?>
return in page
name{"school":{"id":"1234567890","name":"Universiti Tunku Abdul Rahman"},"type":"College"}
i get the college data from Facebook sdk , i only want the school name and store into $_SESSION how am i going to do that? is a array i dont how i going to get the data store into $_SESSION.
Use json_decode to read the array
$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['name']; // Fetches the first name
fbconnect.php
include('functions.php');
connect();
require 'src/facebook.php';
if (!isset($_SESSION['user'])) {
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'GET');
$ret = $facebook->api( array(
'method' => 'fql.query',
'query' => 'SELECT affiliations FROM user WHERE uid = me()',
));
$network = $ret['0']['affiliations']['0']['name'];
//echo $network;
$data = $facebook->api('/me', 'get', array("fields"=>"location"));
$location = $data['location']['name'];
$sql = mysql_query("SELECT * FROM xx_users WHERE user_id=$user_profile[id]");
if (mysql_num_rows($sql) == 0) {
mysql_query("INSERT INTO xx_users (name, user_id, email, network, location)
VALUES ('$user_profile[name]', '$user_profile[id]', '$user_profile[email]', '$network', '$location')");
}
else {
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
// $loginUrl = $facebook->getLoginUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email, user_location, user_work_history, user_education_history', // Permissions to request from the user
'redirect_uri' => 'http://comfyshoulderrest.com/socialexchange/home.php', // URL to redirect the user to once the login/authorization process is complete.
));
}
}
else {
$_SESSION['user'] = $user;
$_SESSION['friends'] = $facebook->api('/me/friends');
// $_SESSION['friends'] = $facebook->api('/$user/friends'); THIS GIVES THE SAME RESULT
}
data.php
include('functions.php');
connect();
session_start();
$friends = $_SESSION['friends'];
$user = $_SESSION['user'];
$arr = $friends['data'];
$friend_ids_arr = array();
foreach ($arr as $friend) { // THIS IS LINE 14
$friend_ids_arr[] = $friend['id'];
}
error:
Warning: Invalid argument supplied for foreach() in /blah/data.php on line 14
Is there anything I'm doing that's preventing the variable from passing?
EDIT
$_SESSION['user'] prints just fine, so I presume the problem lies with this line:
$_SESSION['friends'] = $facebook->api('/me/friends');
I'm not sure how data.php ties into fbconnect.php but maybe you want to use
$friends = $_SESSION['friends'];
before
$arr = $friends['data'];
From what I've seen, on fbconnect.php you didn't start the session. Try inserting session_start(); after connect().
<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
define('APP_ID', '******************');
define('APP_SECRET', '***********************');
$facebook = new Facebook(array(
'appId' => '******************',
'secret' => '***********************',
'cookie' => true
));
$session = $facebook->getSession();
if (!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$uid = $facebook->getUser();
print_r($uid);
$user = $facebook->api('/me');
facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
} catch (Exception $e) {
}
if ($user) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
echo '<pre>';
print_r($user);
echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_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();
$loginUrl = $facebook->getLoginUrl( array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream',
'next' => 'http://localhost/login_twitbook/',
'cancel_url' => 'http://localhost/login_twitbook/'
) );
header("Location: " . $login_url);
}
?>
The $user = $facebook->api('/me'); doesnot working properly its always returns nothing. pls help me to solve this problem. I'm working on localhost.$uid = $facebook->getUser() its returns the value but the $user doesnt return
Try changing the getCode function in the base_facebook.php file change all the $_REQUEST to $_GET. Not sure why this hasn't been fixed yet but I was pulling my hair out trying to figure out why it was returning 0 for the user until I did this, now it works flawlessly.
Should be on or around line 680 of the file and there are 4 to change.
protected function getCode() {
if (isset($_GET['code'])) {
if ($this->state !== null &&
isset($_GET['state']) &&
$this->state === $_GET['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_GET['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
I want to get the facebook $fbme email information using the facebook php SDK.I am getting rest of the information like Firstname,Lastname,Gender but not getting the Email.I have even tried giving the Extended email permissions but that did not help.Please help as soon as possible.
Here is my code
/*
* Sign up procees for facebook login
*/
if (array_key_exists("facebook", $_GET)) {
/*
* Distroy all sesion data
*/
$this->objSession->unsetAll();
/*
* Distroy all api session data
*/
$this->objAPISession->unsetAll();
/*
* if seesion data is not present then facebook login
*/
if (0 == $this->objSession->USRlKey) {
try {
include_once "library/facebook/facebook.php";
} catch (Exception $strError) {
echo "facebook.php File not found on server";
}
$arrConfigSetting['appid' ] = FACEBOOK_API_ID;
$arrConfigSetting['secret'] = FACEBOOK_SECRET_KEY;
$facebook = new Facebook(array(
'appId' => $arrConfigSetting['appid'],
'secret' => $arrConfigSetting['secret'],
'cookie' => true ,
));
$strFacebookUser_id = $facebook->getUser();
$fbme = null;
if ($strFacebookUser_id) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
if ('' != $fbme['id']) {
$this->objAPISession->arrAPIUser['intUsrID'] = $fbme['id'];
$this->objAPISession->arrAPIUser['strFirstName'] = isset($fbme['first_name']) ? $fbme['first_name'] : "";
$this->objAPISession->arrAPIUser['strLastName'] = isset($fbme['last_name']) ? $fbme['first_name'] : "";
$this->objAPISession->arrAPIUser['intUserType'] = 3;
$this->objAPISession->arrAPIUser['strSignUpType'] = "Facebook";
$this->_redirect('/login/emailaddress');
die;
}
} catch (FacebookApiException $e) {
echo $e;
}
} else {
$loginUrl = $facebook->getLoginUrl(array('next' => "http://www.mywebsite.com/facebooklogin_success", 'req_perms' => 'email,read_stream,publish_stream,offline_access'));
//echo("<br>login url=".$loginUrl);
return $this->_redirect($loginUrl);
//return $this->_redirect('login/index');
}
} else {
return $this->_redirect('myprofile/index');
}
}
You need to be using version 3 of the PHP SDK which supports the new OAuth authentication.
Also with version 3 this line should be:
$loginUrl = $facebook->getLoginUrl(array('redirect_uri' => "http://dev.popsip.com/facebooklogin_success", 'scope' => 'email,read_stream,publish_stream,offline_access'));