Create facebook application and fetch friends with profile picture using php and fql

by  
Share:
facebook

Facebook has become an integral part of our lives now. It’s not just about the being social now, developers like us are using their API’s to promote business. I personally love playing with Facebook API. In this tutorial I will explain how to create a facebook application, fetch your personal data, your friends with their profile pics with pagination feature using php and fql.

How to create a facebook application?

To create a facebook application you got to have a facebook account(which I am sure you must have). I have been playing with the facebook apps for quite some time now and there’s been a lot of UI changes in facebook developer zone. I had earlier posted the process of creating facebook application and login with facebook but due to the recent change in the User Interface I have posted it again. Just follow these steps below and you can create a facebook application in about 3 minutes.

Facebook Login with php using facebook php sdk

If you guys read my earlier articles on facebook php integration then there is just one change in the method i.e. page redirection after login, rest all are same.

To get started, start from the configure.php where you have to put facebook application id, app secret code, site url and redirect url. Since in this tutorial you will only fetch friends name. profile pictures so you dont have to use any permission here.

<?php
session_start();
require 'facebook_library/facebook.php';
define("APP_ID", "#YOUR APP CODE HERE#");
define("APP_SECRET", "#YOUR SECRET CODE HERE#");
/* make sure the url end with a trailing slash */
define("SITE_URL", "http://demos.aarafacademy.com/facebook-demo1/");
/* the page where you will be redirected after login */
define("REDIRECT_URL", "http://demos.aarafacademy.com/facebook-demo1/home.php");
/* no need to use any permission */
define("PERMISSIONS", "");

?>

Create an object of facebook and check the login status.
<?php
// create a facebook object
$facebook = new Facebook( array('appId'  => APP_ID, 'secret' => APP_SECRET) );
$userID = $facebook->getUser();

// Login or logout url will be needed depending on current user state.
if ($userID) {
  $logoutURL = $facebook->getLogoutUrl(array('next'=> SITE_URL.'logout.php'));
} else {
  $loginURL = $facebook->getLoginUrl( array('scope' => PERMISSIONS,'redirect_uri' => REDIRECT_URL) );
}

// Only if user is logged in, you an fetch user details
if ($userID) {
  try {
	  $_SESSION["user_id"] = $userID;
    // fetch user details.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
	#debugResults($e);
    $userID = NULL;
  }

}
?>

Add the Login link to your landing page from where user can login to facebook and authorize your app to get the access to use your application.
<a href="<?php echo $loginURL; ?>" title="Login with Facebook">
Login with Facebook
</a>

Similarly for logging out, use the logout link below
<a href="<?php echo  $logoutURL; ?> ">Logout</a>

After user successfully login with facebook and authorize app you can see their personal details by making the graph api call.
<?php
$user_profile = $facebook->api('/me');
print_r($user_profile);
?>

Fetch user friends with profile pictures using fql

Now, every thing is set you can query the facebook database to fetch your friends list. Since your friends list can be have friends upto 10 or 10000 so keeping that in mind, use pagination for them. So you will be fetching 20 friends per page(you can change as per your convenience). In case if you want to know how pagination works try Ajax pagination with php and mysql. Also if you want to see the other fields in the user table take a look at the facebook doc here.

<?php
$fql    =   "SELECT uid, name, profile_url, pic_big FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1 = me() ) ORDER BY name ";
$param  =   array(
    'method'    => 'fql.query',
    'query'     => $fql,
    'callback'  => ''
);
$friendsAll  =   $facebook->api($param);
$totalFriendsCount = count($friendsAll);
?>

You have all your friends so divide them using the pagination technique.
//This checks to see if there is a page number. If not, it will set it to page 1 
if (!(isset($_GET['pagenum']))) { 
    $pagenum = 1; 
} else {
    $pagenum = (int)$_GET['pagenum']; 		
}
//This is the number of results displayed per page 	
$page_rows = 20; 

//This tells us the page number of our last page 
$last = ceil($totalFriendsCount/$page_rows); 

//this makes sure the page number isn't below one, or more than our maximum pages 
if ($pagenum < 1) { 
    $pagenum = 1; 
} elseif ($pagenum > $last)  { 
    $pagenum = $last; 
}

Make the final call. It will only fetch a maximum of 20 friends per page.
<?php
$fql2 = $fql." LIMIT ". (($pagenum - 1) * $page_rows)." ,  ". $page_rows. " ";
$param  =   array(
		'method'    => 'fql.query',
		'query'     => $fql2,
		'callback'  => ''
	    );
$friends   =   $facebook->api($param);
?>

Now that you have your friends data, it’s time to display them.
<?php
for($i=0; $i<count($friends); $i++) {
?>
<div class="col-lg-3 adjustImage">
  <img src="<?php echo stripslashes($friends[$i]["pic_big"]); ?>" class="img-circle" width="200px" height="200px">
  <div class="textContainer caption" >
    <?php echo stripslashes($friends[$i]["name"]); ?>
    <br>
    <a class="btn btn-primary btn-sm" href="<?php echo stripslashes($friends[$i]["profile_url"]); ?>" target="_blank"  >View Profile</a>
  </div>
</div>
<?php
}
?>

Don’t forget to print the list of page numbers from where user can select the pages to navigate friends results.
<ul class="pagination pagination-lg">
<?php
//Show page links
if ($last > 1 ) {
  for($i=1; $i<=$last; $i++) {
?>
<li <?php echo ( $i == $pagenum ) ?  ' class="active" ' : ''; ?>><a href="home.php?pagenum=<?php echo $i ?>"  ><?php echo $i ?></a></li>
<?php } } ?>
</ul>

Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

shivasurya on

osm ! nice one bro! CSS was nice in that demo! +1 for ur demo work!

Reply
Usman Ali on

good work bro

Reply
nikhat on

Excellent work it’s nice….keep it up

Reply
Prathyusha Punni on

i got error is “Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed by the App’s settings. It must match
the Website URL or Canvas URL, or the domain must be a subdomain of one
of the App’s domains.” .could you please tell to me what is my mistake

Reply
Shahrukh Khan on

Your site url must match the site url u gave when creating facebook application. This is the reason why is throwing up the error.

Reply
Vijay Sevlia on

Getting this error.
Fatal error: Uncaught Exception: 601: Parser error: unexpected ‘-‘ at position 129.
thrown in E:wampwwwtestappfacebook_librarybase_facebook.php on line 1271
Please help me.

Reply
Shahrukh Khan on

please check if your LOGIN URL is properly encoded. which maybe the reason for error.

Reply
Alcides R on

Hi friend, could solve this problem?, the same thing is happening to me

Reply
Nazmus Shahadat on

I found thi error
Uncaught Exception: REST API is deprecated for versions v2.1 and higher thrown in E:\xampp\htdocs\fb\facebook_library\base_facebook.php on line 1325

Shahrukh Khan on

this error is not displaying here.

subhendu on

Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher
thrown in C:xampphtdocsbootsubhendu_malesiafacebook_librarybase_facebook.php on line 1271

can any body help me

Reply
Er Manish Carpenter on

Hello Shahrukh Khan

i got the following error in my code downloaded from your link and i was not finding any solution over the net plz fix this Error.
Thanks in advance.

“Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher thrown in E:wampwwwMyProjectfbfriendfacebook-demo1facebook_librarybase_facebook.php on line 1271”

Reply
Shahrukh Khan on

I think it may be a cURL issue. Please check your php.ini file

Reply
Savita on

Create facebook application and fetch friends with profile picture using php and fql
fql queries are deprecated in current version.. I am not getting result using graph api.. please can u do help..
Thank You..

Reply
Shahrukh Khan on

Yes, I will update my tutorial soon. and will let you know about it. Stay connected.

Reply
gunjan on

plz send me facebook_library/facebook.php file

Reply
Shahrukh Khan on

The full source code in bundled in the zip file while is available for download. Please download the file.

Reply
nikihil on

i am getting this error after login to fb Invalid or no certificate authority found, using bundled information

Reply
Shahrukh Khan on

what version of php are you using.

Reply
nikihil on

Xampp v3.2.1

Reply
Shahrukh Khan on

It is working here. Must be any of fb configuration issue.

Reply
Sarah on

Great tutorial ! you saved my day! please tell me how can i remove this error? Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher thrown in base_facebook.php on line 1271. It will be a great favour. Thanks! 🙂

Reply
Shahrukh Khan on

it is working here.

Reply
Peter Josch on

I tried the demo but the script is not working for me as I have heard facebook depreciated there v2.0 api and it does not works with v2.1 api.

If you can create a simple application for me then that would be great! Contact me if you can!

Reply
Shahrukh Khan on

yes you are right, the api has been deprecated and the rumors is been that it will be removed in the coming days.

Reply
Devendra on

[15-Jul-2015 10:36:29 UTC] PHP Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/eugeniai/public_html/facebook/home.php:1) in /home/eugeniai/public_html/facebook/configure.php on line 9
[15-Jul-2015 10:36:30 UTC] PHP Fatal error: Uncaught Exception: 190: Invalid OAuth access token signature. (190)
i have done same as ur tutorial but sir after login into facebook the page will blank and stop
i have check error log in the error log the below error shows please help me to solve this problem

thrown in /home/eugeniai/public_html/facebook/facebook_library/base_facebook.php on line 1271
[15-Jul-2015 10:40:22 UTC] PHP Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/eugeniai/public_html/facebook/home.php:1) in /home/eugeniai/public_html/facebook/configure.php on line 9
[15-Jul-2015 10:40:23 UTC] PHP Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher (12)
thrown in /home/eugeniai/public_html/facebook/facebook_library/base_facebook.php on line 1271

Reply
Shahrukh Khan on

add ob_start() at the first line of your page.

Reply
Devendra on

i have done same as ur tutorial but sir after login into facebook the page will blank and stop
i have check error log in the error log the below error shows please help me to solve this problem

thrown in /home/eugeniai/public_html/facebook/facebook_library/base_facebook.php on line 1271
[15-Jul-2015 10:40:22 UTC] PHP Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/eugeniai/public_html/facebook/home.php:1) in /home/eugeniai/public_html/facebook/configure.php on line 9
[15-Jul-2015 10:40:23 UTC] PHP Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher (12)
thrown in /home/eugeniai/public_html/facebook/facebook_library/base_facebook.php on line 1271

Reply
gurdeep on

your demo is showing error.

Reply
Shahrukh Khan on

have you given permsission

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.