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().
Related
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
<?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
<?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'm using the Facebook PHP integration with CodeIgniter.
I have a problem where I click on the login link, it brings me to the Facebook login, I log in successfully, and when it redirects back to my page, none of the Facebook information has come through. Then if I click the login link again, it immediately logs me in without the need for the Facebook login form. If I were to refresh the page instead of clicking the login link the second time, the Facebook information still wouldn't show.
I feel that it's something to do with the session.
$facebook = $this->facebook;
$user = $facebook->getUser();
$user is always 0 until I click the login link for the second time.
This is the login flow:
I feel as if it's failing at the GET /oath/authorize phase.
public function fb_login() {
$facebook = $this->facebook;
// Get User ID
$user = $facebook->getUser();
$this->session->set_userdata(array('user' => $user));
var_dump($user);
$profile = null;
$logoutUrl = null;
$loginUrl = null;
try {
$profile = $facebook->api('/me');
$this->session->set_userdata(array('profile' => $profile));
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if ($user) {
$url = $this->uri->uri_string();
$url = str_replace('/', '-', $url);
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => site_url('[omitted]/fb_logout'.'/'.$url)));
$this->session->set_userdata(array('logoutUrl' => $logoutUrl));
} else {
$loginUrl = $facebook->getLoginUrl(array('display' => 'touch'));
$this->session->set_userdata(array('loginUrl' => $loginUrl));
}
$facebook_array = array(
'user' => $user,
'profile' => $profile,
'logoutUrl' => $logoutUrl,
'loginUrl' => $loginUrl
);
return $facebook_array;
}
public function view_events($organiser_type) {
$this->load->helper('form');
$organiser_type = urldecode($organiser_type);
$data['organiser_type'] = $organiser_type;
$data['title'] = $organiser_type.' Events';
$data['events'] = $this->trinity_impulse_model->get_events_by_type(
$organiser_type,
array('event_start_date', 'event_start_time'),
array('asc', 'asc'));
$i = 0;
foreach ($data['events'] as $event) {
$data['events'][$i]['event_start_date'] = format_timestamp_to('dateFromDB', $event['event_start_date']);
$data['events'][$i]['event_end_date'] = format_timestamp_to('dateFromDB', $event['event_end_date']);
$data['events'][$i]['event_start_date'] = humanise_date($data['events'][$i]['event_start_date']);
$data['events'][$i]['event_end_date'] = humanise_date($data['events'][$i]['event_end_date']);
$data['events'][$i]['event_start_time'] = format_timestamp_to('shorttime', $event['event_start_time']);
$data['events'][$i++]['event_end_time'] = format_timestamp_to('shorttime', $event['event_end_time']);
}
$facebook_array = $this->fb_login();
var_dump($this->session->userdata('user'));
// Get session values.
/*$data['user'] = $this->session->userdata('user');
$data['profile'] = $this->session->userdata('profile');
$data['loginUrl'] = $this->session->userdata('loginUrl');
$data['logoutUrl'] = $this->session->userdata('logoutUrl');
*/
$data['user'] = $facebook_array['user'];
$data['profile'] = $facebook_array['profile'];
$data['loginUrl'] = $facebook_array['loginUrl'];
$data['logoutUrl'] = $facebook_array['logoutUrl'];
$this->load->view('[omitted]/view_events', $data);
}
EDIT: The other pages in my application work as normal. The login displays Facebook data on first attempt. There is nothing different in the other pages. They all use the fb_login() function in the same manner.
EDIT2: I did var_dump($facebook) to see what was different about the variable on the failed login. I found that the state is set when I encounter the problem. If it is not set, it logs in with no problem. I still don't know how to resolve that though. Here is the var_dump():
["state":protected]=> string(32) "ac816d6fa8fba908b6bd01f3e7f0ec75"
I have resolved this.
I don't know what the cause of the problem was, but I modified the code and now it works. The offending piece of code was:
try {
$profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
I wrapped an if around it so that it was only called if the $user variable was instantiated. Code is like so:
if ($user) {
try {
$profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
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'));