Facebook friend counter - php

What I'm trying to do is a counter of facebook friends in php, so the result of the code would be something like "You have 1342 Friends!".
So this is the code im using:
<?php
require_once("../src/facebook.php");
$config = array();
$config[‘appId’] = 'MY_APP_ID';
$config[‘secret’] = 'MY_APP_SECRET';
$facebook = new Facebook($config);
$user_id = "MY_USER_ID";
//Get current access_token
$token_response = file_get_contents
("https://graph.facebook.com/oauth/access_token?
client_id=$config[‘appId’]
&client_secret=$config[‘secret’]
&grant_type=client_credentials");
// known valid access token stored in $token_response
$access_token = $token_response;
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Query the graph - Friends Counter:
$data = file_get_contents
("https://graph.facebook.com/$user_id/friends?" . $access_token );
$friends_count = count($data['data']);
echo "Friends: $friends_count";
echo "<p>$data</p>"; //to test file_get_contents
?>
So, the result of the echo $Friends_count its always "1".
And then I test $data with an echo and it give me the list of all the friends so it is getting the content but its not counting it right... how could i fix it?
I've already tried changing the
$friends_count = count($data['data']);
for
$friends_count = count($data['name']);
and
$friends_count = count($data['id']);
but the result is always "1".
The result of the above code looks like this;
Friends: 1
{"data":[{"name":"Enny Pichardo","id":"65601304"},{"name":"Francisco Roa","id":"500350497"},etc...]

You have a JSON object; a string, not anything PHP can "count" with count(). You need to parse the JSON first:
$obj=json_decode($data);
$friends_count = count($obj->data); // This refers to the "data" key in the JSON
Some references I quickly googled:
http://php.net/manual/en/function.json-decode.php
http://roshanbh.com.np/2008/10/creating-parsing-json-data-php.html

You can get friend count by fql easily.
There is a friend_count field against the user table that you can query.
SELECT friend_count FROM user WHERE uid = me();
https://graph.facebook.com/fql?q=SELECT friend_count FROM user WHERE uid={any id}

Related

How do you get user OAuth for the Tumblr API in PHP?

Using the default Tumblr v2 API, I'm able to connect to my application, and retrieve posts from my own account. However, I'd like users to be able to connect their own accounts. I've tried to figure this out but I'm not entirely sure how to use OAuth (im using this class). How is this done?
The code I'm using to retrieve dashboard posts is:
$consumerKey = 'xxx';
$consumerSecret = 'xxx';
$tumblr = new Tumblr\API\Client(
$consumerKey,
$consumerSecret
);
var_dump( $tumblr->getDashboardPosts() ); // using var_dump for testing purposes only
This code works, but it's only returning the code for my PERSONAL account.
I figured it out, thanks to Github user seejohnrun.
require_once 'include/util.php';
$consumerKey = 'XXX';
$consumerSecret = 'XXX';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// If we are visiting the first time
if (!$_GET['oauth_verifier']) {
// grab the oauth token
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// tell the user where to go
echo ' GO ';
$_SESSION['t']=$data['oauth_token'];
$_SESSION['s']=$data['oauth_token_secret'];
} else {
$verifier = $_GET['oauth_verifier'];
// use the stored tokens
$client->setToken($_SESSION['t'], $_SESSION['s']);
// to grab the access tokens
$resp = $requestHandler->request('POST', 'oauth/access_token', array('oauth_verifier' => $verifier));
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// and print out our new keys we got back
$token = $data['oauth_token'];
$secret = $data['oauth_token_secret'];
echo "token: " . $token . "<br/>secret: " . $secret;
// and prove we're in the money
$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
$info = $client->getUserInfo();
echo "<br/><br/>congrats " . $info->user->name . "!";
}

How to use setExtendedAccessToken()

i am using Graph api to create a facebook app with PHP .
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'xxxxxxxxxxx';
$config[‘secret’] = 'xxxxxxxxxxxxxxxxxxxxx'; // NEVER USED THIS , JUST INCLUDED IT !
$config[‘fileUpload’] = true; // optional
$facebook = new Facebook($config);
$app_id = "xxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token']; // The acess call :)
$at = $params['access_token']; // I USE THIS ACCESS TOKEN
I now use that access token ($at) to make requests . But i need to store the access_token for much longer time (60 days) .
So
1)how do i use setExtendedAccessToken() method &
2) where i should put that in my code &
3) where can i obtain the output from
I am including the PHP SDK too , even though i am not using it .
You can exachange temporary Token for Extended Token. check below code.
try {
$graph_url = "https://graph.facebook.com/oauth/access_token?";
$graph_url .= "client_id=".$FB_APP_ID;
$graph_url .= "&client_secret=".$FB_APP_SECRET;
$graph_url .= "&grant_type=fb_exchange_token";
$graph_url .= "&fb_exchange_token=".$fb_temp_access_token;
$response = #file_get_contents($graph_url);
$params = null;
parse_str($response, $params);
$new_token =$params['access_token'];
} catch (Exception $e) {
//DO NOTHING
}
You can extend an access_token, read about it here: https://developers.facebook.com/docs/howtos/login/extending-tokens/
Put it at the end, after you have already have an acces_token from the login.
You get the output in the same manner you would with other API calls.
The code I am using to get access token is:
$access_token=$facebook->getAccessToken();
I just put this code like this.
if($userid){
try{
$access_token = $facebook->getAccessToken();
echo $access_token;
}
catch(FacebookApiException $e){
//catch error here
}
else{
$loginUrl=$facebook->getLoginUrl(array('redirect_uri'=>'your_url','scope'=>'publish_stream,read_stream,manage_pages');
exit("<script>window.top.location.replace('$loginUrl');</script>");
}
It does store access token that will expire about 2 month ( I use this tool to check).

Twitter OAuth returning blank array if there is no tweet

I spent my last 5 hours in this issue and finally I came here for the solution.
I am doing log-in using twitter functionality in my site (Zend Framework + PHP) and everything is working fine. But I am facing the following issue in it:
If the user has no tweets (0 tweets) in his account then the
$tweets = json_decode($response->getBody());
echo "<pre>";
print_r($tweets);
exit;
Its showing me blank array. i.e. : Array(); :-(
And if I am adding some tweets there in twitter account then its showing me the complete array along with user information like display name, image, etc...like this:
Array
(
//other data
[0] => stdClass Object
(
[user] => stdClass Object
....
....
so on..
)
)
Following is my code :
public function twitterregisterAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
session_start();
require $path . "/Zend/Oauth/Consumer.php";
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION["TWITTER_REQUEST_TOKEN"] = serialize($token);
// redirect the user
$consumer->redirect();
}
/*
* Ticket id #16
* twittercallbackAction method
*/
public function twittercallbackAction() {
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!$this->_getParam("denied")) {
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
// save token to file
// file_put_contents('token.txt', serialize($token));
$client = $token->getHttpClient($config);
$client->setUri('https://api.twitter.com/1/statuses/user_timeline.json?');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('name');
$client->setParameterGet('profile_image_url');
$response = $client->request();
$tweets = json_decode($response->getBody());
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $tweets[0]->user->id;
$session->tw_name = $tweets[0]->user->name;
$session->tw_image = $tweets[0]->user->profile_image_url;
if ($session->tw_id != "") {
$tw_id = $session->tw_id;
//Calling the function twitterAuthAction for email authentication
$twAuthArr = $this->twitterAuthAction($tw_id);
if ($twAuthArr['socialId'] == $tw_id) {
$session->userId = $twAuthArr['id'];
$session->email = $twAuthArr['emailId'];
$this->_redirect('/profile/showprofile');
} else {
$user = new UserRegistration();
$firstname = "";
$lastname = "";
$password = "";
$socialtype = "twitter";
$email = "";
$socialid = $session->tw_id;
$result = $user->registerUser($firstname, $lastname, $socialid, $socialtype, $email, $password);
$session->userId = $result;
$this->_redirect('/register');
}
}
$this->_redirect("/register");
} else {
$this->_redirect("/register");
}
}
My Questions are :
1) Why its not providing user array if there is no any tweet in my twitter account (or newly created twitter account)
2) I want user profile details from twitter account. How can I get it?
Need Help. Thanks
I think as per david's answer you need to use users/show url there instead of using statuses/user_timeline. You can use curl for requesting url so you'll get the response which contains the users information.
Try with following code:
$user_id = $client->getToken()->getParam('user_id');
$trends_url = "http://api.twitter.com/1/users/show.json?user_id=".$user_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $response['id'];
$session->tw_name = $response['name'];
$session->tw_image = $response['profile_image_url'];
Try this. Hope it will help you.
I think you are misreading the Twitter API docs for the statuses/user_timeline endpoint.
The field user that you identify is one of the fields within a returned tweet. If the user id to which you point has no tweets, then there will be no entries in the returned array, hence no user field.
If you need the user information even in the absence of any tweets, then you probably need to hit the users/show endpoint.

Facebook FQL getting status does not work and returns empty list

I just followed the sample in here https://developers.facebook.com/docs/reference/fql/ , but I replaced the query with like this https://developers.facebook.com/docs/reference/fql/status/ but I replaced the uid with me()
So here's my code:
$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url)
. '&client_secret=' . $app_secret
. '&code=' . $code;
$access_token = file_get_contents($token_url);
$q = urlencode("SELECT status_id, message FROM status WHERE uid=me()");
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q='.$q
. '&' . $access_token;
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);
echo '<pre>';
print_r("query results:");
print_r($fql_query_obj);
echo '</pre>';
This one does not return anything. It just gives me an empty array.
This is already the permission of my app:
I don't know what's the problem in here anymore. I'm sure that my app Id and secret key are correct.
What's wrong with this code? i'm getting an empty list. It's not fetching my status updates. Your help would be greatly appreciated and rewarded!
Thanks!
That permission is just for the settings. It doesn't signify whether each individual user has granted permissions.
Try /me/permissions?fields=read_stream on the user with the correct access token to see whether the user has given permission.
You should get
{
"data": [
{
"read_stream": 1
}
]
}
Once you are sure that is set then it should work. A quick way to check would be try it in the Graph Explorer against your access token
https://developers.facebook.com/tools/explorer?fql=SELECT%20status_id%2C%20message%20FROM%20status%20WHERE%20uid%3Dme()
Encounter same problem here, to make sure the user have granted "read stream" permission, here is what I did:
$params = array(
'scope' => 'read_stream'
);
$loginUrl = $facebook->getLoginUrl($params);

How to parse the authentication code in the Facebook API? Getting MySQL errors

What's the right way to parse the code when authenticating your app during a user login? I'm using PHP for my app.
The reason I'm asking is because I keep getting weird queries in MySQL whenever I try to do inserts into my database. The API calls are all working, but if I try to put in user details (name, email, access_token) then three or four other queries will also run after that with empty values, each in different rows. This only happens when I try to get the authentication code via $_REQUEST['code'] or $_SERVER['QUERY_STRING'] after the dialog url.
What's weird though is that I don't get any issues with MySQL at all if I simply try calling the same page with $code hard-coded to the right value. Obviously, I can't leave it like that since the authentication code is always changing, but it's weird because only then do my MySQL work normally. Has anyone else experienced this? Is the code response encoded in a different format maybe?
Any help would be greatly appreciated, here's my code:
$code = $_REQUEST['code'];
if (empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id .
"&redirect_uri=" . urlencode($redirect) . "&scope=offline_access,email";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
$response = urldecode($_SERVER['QUERY_STRING']);
$code = substr($response,5);
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($redirect) . "&client_secret=" .
$app_secret . "&code=" . $code;
$access_token = file_get_contents($token_url);
$user_url = "https://graph.facebook.com/me?" . $access_token;
$user = json_decode(file_get_contents($user_url));
$user_id = $user->id;
$email = $user->email;
// MYSQL insert queries into database
Are you using the facebook php sdk file? or are you making your own authorization callback?
because its much easyer, example:
////////////////////////////////////////////////////////
require_once('facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
$sql=my_sql_fetch_array(mysql_query("SELECT * from mytable where id='".$me['id']."'"));
if($sql)
{
$_SESSION["usr_id"] =$me['id'];
$_SESSION["usr_name"]=$me['name'];
}
else{
mysql_query("insert into mytable (id,fbid,name) values(NULL,'".$me['id']."','".$me['name']."'");
$_SESSION["usr_id"] =$me['id'];
$_SESSION["usr_name"]=$me['name'];
}
} else {
$loginUrl = $facebook->getLoginUrl();
}
//i set sessions here or maybe some mysql commands like check if the user is already in the database and then set the sessions.

Categories