PHP / Facebook-Api: Update Friendlist - php

I'm using the official PHP-Facebook-Api and I know how to get the friendlist of a user. It is basically like so:
$facebook = new Facebook(array(
'appId' => 'xxxxxxxx',
'secret' => 'xxxxxxx',
'cookie' => true,
));
// $session is only != null, when you have the session-cookie, that is set by facebook, after the user logs in
$session = $facebook->getSession();
// you dont get a list of friends, but a list, which contains other friendlists
$friendsLists = $facebook->api('/me/friends');
// Save all Friends and FriendConnections
foreach ($friendsLists as $friends) {
foreach ($friends as $friend) {
// do something with the friend, but you only have id and name
$id = $friend['id'];
$name = $friend['name'];
}
}
In my Application I basically save all Friends in my database, so that I dont have make an http-request everytime I want to show all Friends of a user. But now I would like to update the Friendlist. I would hate to delete all friend-Connections and save them all over again. So does anybody know about an option, how to just get the changes of the friendlist since a certain date?

Your going to have to check if they are in the database then. I suggest you get an array of all the user id's in the database and then check them against the friends you pulled from the API. If there is a new friend, add them.
$database = new mysqli('Localhost', 'username', 'password', 'db_name');
if($users = $database->query('SELECT id FROM `users`')) {
while($row = $result->fetch_assoc()) {
$my_friend[] = $row['id'];
}
}
$facebook = new Facebook(array(
'appId' => 'xxxxxxxx',
'secret' => 'xxxxxxx',
'cookie' => true,
));
// $session is only != null, when you have the session-cookie, that is set by facebook, after the user logs in
$session = $facebook->getSession();
// you dont get a list of friends, but a list, which contains other friendlists
$friendsLists = $facebook->api('/me/friends');
// Save all Friends and FriendConnections
foreach ($friendsLists as $friends) {
foreach ($friends as $friend) {
// do something with the friend, but you only have id and name
$id = $friend['id'];
$name = $friend['name'];
if(!in_array($id, $my_friends)) {
// Insert into table
}
}
}

Related

Get facebook education into $_SESSION

<?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

FB API inserting user_id that belongs to Open User account

This is easily the most bizarre problem that I've ever run into while using the FB api. Maybe I'm just too much of a n00b with their API, but here goes.
I'm using the login button for my site. Upon click, the user will be presented with a pop up from FB telling them some basic info about my app (basic details, number of active users and permissions that it is requesting)
That's all fine and dandy. If the user accepts the app, the page will be reloaded and their info that is being requested from the app will be inserted into the DB and a session will be created.
session_start();
require_once("model/functions.php");
require_once("controller.php");
require_once("model/facebook_api/src/facebook.php");
$facebook = new Facebook(array(
'appId' => '123456789',
'secret' => '123456789',
'cookie' => true
));
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
if($access_token != "")
{
$user = $facebook->getUser();
if($user != 0)
{
$user_profile = $facebook->api("/".$user);
$fb_id = $user;
$fb_first_name = $user_profile['first_name'];
$fb_last_name = $user_profile['last_name'];
$fb_email = $user_profile['email'];
// The FB user_id and all of their other info is correct. Seriously!!
echo $fb_id."<br />";
print_r($user_profile);
// Query the DB to see if this person's info from FB is in there
$query = "SELECT *
FROM users
WHERE fb_id = :fb_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':fb_id' => $fb_id));
$count = $stmt->rowCount();
if($count == 1)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row['user_id'];
$_SESSION['fb_id'] = $row['fb_id'];
$_SESSION['first'] = $row['first_name'];
$_SESSION['last'] = $row['last_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['accuracy'] = $row['accuracy_rate'];
}
} else
{
$img_data = file_get_contents('https://graph.facebook.com/'.$fb_id.'/picture?type=large');
$save_path = 'img/profile_pics/large/';
file_put_contents($save_path.''.$fb_id.'.jpg', $img_data);
$insert = "INSERT INTO
users
(first_name,
last_name,
email,
photo,
fb_id,
accuracy_rate,
date_joined,
date_joined_int)
VALUES
(:first_name,
:last_name,
:email,
:photo,
:fb_id,
:points,
:date_joined,
:date_int)";
$params = array(':first_name' => $fb_first_name,
':last_name' => $fb_last_name,
':email' => $fb_email,
':photo' => $fb_id.'.jpg',
':fb_id' => $fb_id,
':points' => '100',
':date_joined' => date("M j, Y"),
':date_int' => idate('z'));
$stmt = $db->prepare($insert);
$stmt->execute($params)or die('error');
print_r($params);
// Query the DB to see if this person's info from FB is in there
$query = "SELECT *
FROM users
WHERE fb_id = :fb_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':fb_id' => $fb_id));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row['user_id'];
$_SESSION['fb_id'] = $row['fb_id'];
$_SESSION['first'] = $row['first_name'];
$_SESSION['last'] = $row['last_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['accuracy'] = $row['accuracy_rate'];
}
}
} else
{
}
} else
{
}
A row is inserted into the DB each time the page is refreshed. No session is ever created. What's even stranger is that the facebook id that is inserted into the fb_id column in the DB belongs to an account that belongs to a test account that FB uses to test open graph actions that are submitted for approval. I know because after taking a deeper look at the DB, I saw a row in the DB that belonged to an FB open graph actions testers. The ID is "2147483647." That is clearly not the ID that is printed out when I printed out the $user_profile array. Furthermore, after the first time the page is reloaded, an insert query shouldn't even occur because the rowCount returned is set to 1. The insert query is only supposed to be executed if the user is a first time user. Sandbox mode isn't on. I thought might have had something to do with it. But, it didn't.
On an unrelated note, is there a bug with FB's api when it comes to doing
$facebook->api("/me");
That doesn't seem to work.
$facebook->api("/".$user);
seems to work just fine though.
Live example can be found here
Facebook user_id could go beyond the supported Integer length. Discovered this on iPhone SDK for a long ID eg. '10000328862128237'. I suspect that is your problem too as I got the exact same number '2147483647'.

Facebook PHP SDK session variable not passing

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().

Not getting $fbme['email'] in the facebook $fbme object

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'));

facebook invite not getting deleted

I'm using facebook function to delete an invite from notifications and application page tab after the invite is accepted but it is giving me a error.
function build_full_request_id($request_id, $user_id) {
echo $request_id . '_' . $user_id;
}
foreach ($request_ids as $request_id)
{
("reqeust_id=".$request_id."<br>");
$full_request_id = build_full_request_id($request_id, $user_id);
("full_request_id=".$full_request_id."<br>");
try {
$delete_success = $facebook->api("/$full_request_id",'DELETE');
if ($delete_success) {
echo "Successfully deleted " . $full_request_id;}
else {
echo "Delete failed".$full_request_id;}
}
catch (FacebookApiException $e) {
"error";}
}
This is the error,i get Call to a member function api() on a non-object in
wow, you have so many errors in your "code" i wonder that it only fails with the non-object error. try this one:
$facebook = new Facebook(array(
'appId' => '1231231231231',
'secret' => '12ba5212bae2617267',
));
foreach ($request_ids as $request_id) {
$full_request_id = $request_id."_".$user_id;
try {
$delete_success = $facebook->api('/'.$full_request_id, 'DELETE');
if ($delete_success) {
echo "Successfully deleted ".$full_request_id;
}else{
echo "Delete failed ".$full_request_id;
}
} catch(FacebookApiException $e) {
echo $e->getMessage();
}
}
The error means that your variable $facebook is not an object. Find the place in your code where $facebook is created and make sure you are generating it correctly. It should look something like this:
$facebook = new Facebook(array(
'appId' => '1231231231231',
'secret' => '12ba5212bae2617267',
));
(Obviously, it should have your appId and secret rather than the junk ones I put in there.)

Categories