Truemag

  • Categories
    • Tips And Tricks
    • Internet
    • PHP
    • Javascript
    • CSharp
    • SQL Server
    • Linux
  • Lastest Videos
  • Our Demos
  • About
  • Contact
  • Home
  • Write With Us
  • Job Request
Home Facebook Graph API PHP Load And Save Facebook Friend List

PHP Load And Save Facebook Friend List

This tutorial simply use Facebook Graph API to load all your friends in Facebook. And in order to avoid connecting to Facebook all the time, we will store all friend IDs to MySQL database since your friend may not change (add or remove) their friend list very often. In addition, using pagination (paging) is a good idea to optimize the response time and easier to navigate as people can have few thousands friends in their list.

To make it simple, I’ll place everything in one file, includes:

  • 1. Facebook application configuration (app id and app secret), request allow permission and request friend list using Facebook Graph API.
  • 2. MySQL connection and manipulation; check and save Facebook user Id and friend list. As I mentioned above, pulling the friend list from Facebook may take a while if you have a lot of friends and the list won’t be changed often therefore we should store the list somewhere to reduce the loading time if the user comes back. In this case, I use MySQL database as an example and you can use another method such as file storage or any cache mechanic and you also should have a schedule to renew the list.
  • 3. Display Facebook friend list in a table with pagination
  • 4. Create page navigation function with some input parameters
  • 5. Resize Facebook app in the iframe in case your Canvas is higher than 800px.
  • 6. Calculate the execution time to evaluate the response time

1. Php load Facebook friend list from MySQL database with paging

[php highlight=”9,10,18,36,37,38,39,51,55,60,75,100,117,170,176″] <?php
$start_process = (float) array_sum(explode(‘ ‘,microtime()));
ini_set(‘display_errors’, 1);
error_reporting(E_ALL);

require ‘src/facebook.php’;

$facebook = new Facebook(array(
‘appId’ => "_your_app_id_",
‘secret’ => "_your_app_secret_",
));

$user_id = $facebook->getUser();

if($user_id == 0 || $user_id == "")
{
$login_url = $facebook->getLoginUrl(array(
‘redirect_uri’ => "http://apps.facebook.com/rapid-apps/",
‘scope’ => "email,publish_stream,user_hometown,user_location,user_photos,friends_photos,
user_photo_video_tags,friends_photo_video_tags,user_videos,video_upload,friends_videos"));

echo "<script type=’text/javascript’>top.location.href = ‘$login_url’;</script>";
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<div id="fb-root">
<?php
$db_host = "localhost";
$db_name = "_your_db_name_";
$db_username = "_your_db_user_";
$db_password = "_your_db_password_";

$dbh = mysql_connect($db_host, $db_username, $db_password) or die("Unable to connect to MySQL");
mysql_query(‘SET NAMES "utf8"’);
mysql_select_db($db_name, $dbh) or die("Could not select $db_name");

echo "<p>Your Facebook Id: " . $user_id . "</p>";

$total_friend = 0;
$sql = "select * from fb_users where uid='{$user_id}’";
$q = mysql_query($sql);
if(!$r = mysql_fetch_array($q)){
$friends = $facebook->api("/me/friends");

$total_friend = count($friends["data"]);

mysql_query("insert into fb_users(uid, total_friend) values (" . $user_id . ", " . $total_friend . ")");

$count = 0;

$friend_ids = "";
$query = "insert into fb_friends(uid, friend_id, friend_name)values";
$values = "";

foreach($friends["data"] as $item){
$friend_ids .= $item["id"] . ",";
$values .= "(‘{$user_id}’, ‘{$item["id"]}’, ‘" . mysql_escape_string($item["name"]) . "’)," ;
}

if($values != ""){
$values = substr($values, 0, strlen($values) -1);
$values .= ";";
}

$query .= $values;

mysql_query($query);
}
else
{
$total_friend = $r["total_friend"];
}

$page = 0;

if(isset($_REQUEST["page"]) && $_REQUEST["page"] != "")
$page = (int)$_REQUEST["page"];
if($page == 0)$page = 1;

$page_size = 10;

$total_pages = ceil($total_friend/$page_size);

if($page > $total_pages)
$page = $total_pages;

$start = $total_pages > 0 ? (( $page * $page_size ) – $page_size) : 0;
$end = $start + $page_size;
$start = $start <= 1 ? 0 : $start;
$sql .=" LIMIT $start, $page_size";

$sql = "select * from fb_friends where uid='{$user_id}’ LIMIT $start, $page_size";

$q = mysql_query($sql);
$friend_table = "";
$friend_table .= "<table border=’1′>";
$friend_table .= "<tr><th>Friend Name</th><th>Friend Facebook Id</th><th>Friend Picture</th></tr>";
while($r = mysql_fetch_assoc($q))
{
$friend_table .= "<tr><td>" . $r["friend_id"] . "</td><td>" . $r["friend_name"] . "</td><td align=’center’><img src=’http://graph.facebook.com/" . $r["friend_id"] . "/picture’></td></tr>";
}
$friend_table .= "</table>";

echo "<h3>Your Facebook Friend List ({$total_friend} friends)</h3>";
echo $friend_table;

echo create_page_navigation($total_friend, $page, $page_size, "https://apps.facebook.com/rapid-apps/load-friends.php", "");

function create_page_navigation($total_record, $current_page_, $item_per_page, $url, $query_string)
{
$current_page = $current_page_ + 1;
$pagerange = 10;
$num_pages = ($total_record % $item_per_page == 0) ? ceil($total_record / $item_per_page) : ceil($total_record / $item_per_page);

$rangecount = 0;
$table = "<table>";
$table .= "<tr>";
$table .= "<td>{$current_page_ } / {$num_pages} </td>";
if ($current_page_ > 1)
{
$tmp = $current_page_ – 1;
$table .= "<td><a target=’_top’ href=’" . $url . "?page=" . $tmp . "&&" . $query_string . "’><</a></td>";
}

if ($num_pages > 1)
{
$rangecount = ceil($num_pages / $pagerange);

$startpage = 0;
$count = 0;
for ($i = 1; $i < $rangecount + 1; $i++)
{
$startpage = (($i – 1) * $pagerange) + 1;
$count = min($i * $pagerange, $num_pages);
if ((($current_page >= $startpage) && ($current_page <= ($i * $pagerange))))
{
for ($j = $startpage; $j < $count + 1; $j++)
{
if ($j == $current_page_)
{
$table .= "<td><b>" . $j . "<b></td>";
}
else
{
$table .= "<td><a target=’_top’ href=’" . $url . "?page=" . $j . "&&" . $query_string . "’>" . $j . "</a></td>";
}
}
}
}
}
if ($current_page_ < $num_pages)
{
$tmp2 = $current_page_ + 1;
$table .= "<td><a target=’_top’ href=’" . $url . "?page=" . $tmp2 . "&&" . $query_string . "’>></a></td>";
}
$table .= "</tr></table>";
return $table;
}
?>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.Canvas.setSize({ width: 520, height: 1500});
</script>
</body>
</html>
<?php
$end_process = (float) array_sum(explode(‘ ‘,microtime()));
echo "<p>Execution time: ". sprintf("%.4f", ($end_process-$start_process))." seconds</p>";
?>
[/php]

2. Example of load Facebook friend list with paging

load-facebook-friend-list-with-paging

load-facebook-friend-list-with-paging

In the PHP source code above, there are 2 MySQL tables we need to create in order to store Facebook users (table: fb_users) and their friend list (table: fb_friends)

+ fb_users:

[sql] CREATE TABLE IF NOT EXISTS `fb_users` (
`id` int(11) NOT NULL auto_increment,
`uid` bigint(50) NOT NULL,
`total_friend` int(11) NOT NULL,
`last_get_friend` datetime NOT NULL,
`created_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_fb_users_uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
[/sql]

+ fb_friends:

[sql] CREATE TABLE IF NOT EXISTS `fb_friends` (
`id` int(11) NOT NULL auto_increment,
`uid` bigint(50) NOT NULL,
`friend_id` bigint(50) NOT NULL,
`friend_name` varchar(250) NOT NULL,
`created_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_fb_friends_uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=139 ;
[/sql]

Note: replace “_your_app_id_”, “_your_app_secret_” and “redirect_uri” values with your configuration settings. And replace “_your_db_name_”, “_your_db_user_”, “_your_db_password_” with your database connection settings.

+ View demonstration on my Facebook page
+ Download the PHP source code above as well as the current Facebook PHP SDK

Nov 9, 2011Hoan Huynh
Load And Save Facebook Profile Picture Of UserCollabtive: Class DateTimeZone could not be located
You Might Also Like:
  • PHP Load Facebook Albums And Save To MySQL Database
  • Load And Save Facebook Profile Picture Of User
  • Suggest Facebook Fan Page To All Friends
  • Facebook Load User Profile Via Graph API And FQL Query
  • Ways To Increase Facebook Fans
  • PHP Check If User Like Facebook Page
  • Show Latest People Of Facebook Fan Page
  • Add Notes Applications To Facebook Fan Page
  • Facebook Like Button And Recommend Button With fb:like, iframe and html5
  • How To Delete Application In Facebook Developers
Hoan Huynh

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at [email protected]

9 years ago Facebook Graph APIFacebook, mysql_query, setSize398
0
GooglePlus
0
Facebook
0
Twitter
0
Digg
0
Delicious
0
Stumbleupon
0
Linkedin
0
Pinterest
Most Viewed
PHP Download Image Or File From URL
22,195 views
Notepad Plus Plus Compare Plugin
How To Install Compare Text Plugin In Notepad Plus Plus
20,069 views
Microsoft SQL Server 2008 Attach Remove Log
Delete, Shrink, Eliminate Transaction Log .LDF File
15,846 views
JQuery Allow only numeric characters or only alphabet characters in textbox
13,323 views
C# Read Json From URL And Parse/Deserialize Json
9,815 views
4 Rapid Development is a central page that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers.
Recent Posts
  • Free Online Photo Editor
  • Easy Tips For Writing An Essay
  • What Can I Expect From An Academic Essay Service?

  • Can Be Essay Service Companies Good For You?

  • Tips To Choosing The Ideal Essay Writers
Categories
  • CSharp (45)
  • Facebook Graph API (19)
  • Google API (7)
  • Internet (87)
  • iPhone XCode (8)
  • Javascript (35)
  • Linux (28)
  • MySQL (16)
  • PHP (84)
  • Problem Issue Error (29)
  • Resources (32)
  • SQL Server (25)
  • Timeline (5)
  • Tips And Tricks (141)
  • Uncategorized (112)
Recommended
  • Custom Software Development Company
  • Online Useful Tools
  • Premium Themes
  • VPS
2014 © 4 Rapid Development