PHP Load And Save Facebook Friend List
Posted by in Facebook Graph API November 9, 2011 1 Comment

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
	$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>";
?>

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:

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 ;

+ fb_friends:

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 ;

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

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • Shanky2704

    hey Hoan,
    Thank you for the code. Exactly what i was looking for.
    But, I am getting the following error-
    “You don’t have permission to access the requested object. It is either read-protected or not readable by the server.
    If you think this is a server error, please contact the webmaster.
    Error 403
    127.0.0.106/25/12 13:23:58Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1″

    Cant get my head around the same. Please help me out.
    Thank you.