How to fetch your facebook friends birthday using php and fql

by  
Share:
facebook

In this tutorial you will learn how to fetch your facebook friends birthday details using php and fql. You can then use this birthday information to send greeting to your friends/ or customers who have registered to your website via facebook Login. I have used facebook query language (fql) to retrieve the information with the facebook library class.

Create a new facebook application in order to run this demo. If you want to learn how to create new application or learn the basics of the facebook api then see my previous tutorial about facebook login with php and facebook sdk.

These permission are needed to run the script:

user_birthday and friends_birthday.

Setup the configuration file with application id and secret key along with the site url and user permission to the application.

session_start();
require 'facebook_library/facebook.php';
define("APP_ID", "XXXXXXXXXXXXX");
define("APP_SECRET", "XXXXXXXXXXXXXXXXXXXXXXX");
define("SITE_URL", "http://demos.aarafacademy.com/facebook-birthday/");
define("PERMISSIONS", "user_birthday,friends_birthday");

Applying the condition for login. If user already is logged in, fetch the user specific details else make user login with the application.
// 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' => SITE_URL) );
}

// Only if user is logged in, we 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;
  }

}

The home page from where user can logs in to facebook and authorize the application. its been named index.php
<?php
require_once("configure.php");
if (isset($_SESSION["user_id"]) && $_SESSION["user_id"] != "" ) {
	// user already logged in the site
	redirectURL(SITE_URL."home.php");
}
?>
<a href="<?php echo $loginURL; ?>" title="Login With Facebook" ><img src="facebook_login.png" width="209" height="40" border="0" alt="Facebook Login" /></a>

The most crucial part of the code is the fql part where you will fetch the friends birthday with facebook query language. It will return an array of data on successful execution.
<?php
  try {

	$fql = "SELECT uid,name,pic_small,birthday_date,birthday FROM user WHERE strlen(birthday_date) <> 0 
			AND  uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) order by birthday_date ASC ";

	$user_friends = $facebook->api(array( 'method' => 'fql.query','access_token' =>  $access_token, 'query' => $fql , 'callback'  => '' ));
	#debugResults($user_friends);	
  } catch (FacebookApiException $e) {
	#debugResults($e);
  }

?>

Now the most easiest of them all. Just output all the results i.e. friends birthday.
<div class="friendBox">
    <?php 
	if(count($user_friends) > 0 ) { 
		foreach($user_friends as $friends) {
	?>
	<div>
	<em><?php echo stripslashes($friends["name"]); ?></em><br>
    <img src="https://graph.facebook.com/<?php echo $friends["uid"]; ?>/picture" height="50;" alt="">
    <div style="text-align:center; width:96%;"><strong><?php echo stripslashes($friends["birthday"]); ?></strong></div>
    </div>

     <?php } } else {  ?>
      <div class="title" style="width:100%;">Look like no one is having birthday this month. no party guys :( </div>
     <?php } ?>
    </div>

Search friends birthday by month

Now let’s make things a bit easier for end user (always complicated for programmer) by showing user birthday only for a specific month.

Create a dropdown with months name and values.

<select name="month" onChange="showByMonth(this.value)">
        <option value=''   <?php echo (!isset($_REQUEST["month"]) || $_REQUEST["month"] == "" )  ? "selected" : ""; ?>>--Select Month--</option>
        <option  value='1' <?php echo ($_REQUEST["month"] == 1)  ? "selected" : ""; ?>  >January</option>
        <option value='2'  <?php echo ($_REQUEST["month"] == 2)  ? "selected" : ""; ?>>February</option>
        <option value='3'  <?php echo ($_REQUEST["month"] == 3)  ? "selected" : ""; ?>>March</option>
        <option value='4'  <?php echo ($_REQUEST["month"] == 4)  ? "selected" : ""; ?>>April</option>
        <option value='5'  <?php echo ($_REQUEST["month"] == 5)  ? "selected" : ""; ?>>May</option>
        <option value='6'  <?php echo ($_REQUEST["month"] == 6)  ? "selected" : ""; ?>>June</option>
        <option value='7'  <?php echo ($_REQUEST["month"] == 7)  ? "selected" : ""; ?>>July</option>
        <option value='8'  <?php echo ($_REQUEST["month"] == 8)  ? "selected" : ""; ?>>August</option>
        <option value='9'  <?php echo ($_REQUEST["month"] == 9)  ? "selected" : ""; ?>>September</option>
        <option value='10' <?php echo ($_REQUEST["month"] == 10)  ? "selected" : ""; ?>>October</option>
        <option value='11' <?php echo ($_REQUEST["month"] == 11)  ? "selected" : ""; ?>>November</option>
        <option value='12' <?php echo ($_REQUEST["month"] == 12)  ? "selected" : ""; ?>>December</option>    
    </select>

Bind the dropdown change event to a javascript function.
<script type="text/javascript">
function showByMonth(monthValue) {
	//alert(monthValue);
	var str = '<?php echo SITE_URL ?>home.php';
	if (monthValue.length > 0 ) {
		str = "?month="+monthValue;
	}
	window.location = str;
}
</script>

Coding keeping in mind that user can search by month as well.
<?php
  try {
	// fetch user details.
	$monthQuery = "";
	if (isset($_REQUEST["month"]) && $_REQUEST["month"] <> "" ) { 
		$monthQuery = " AND substr(birthday_date,0,2) = '". $_REQUEST["month"]. "'";
	}

	$fql = "SELECT uid,name,pic_small,birthday_date,birthday FROM user WHERE strlen(birthday_date) <> 0 $monthQuery	
			AND  uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) order by birthday_date ASC ";

	$user_friends = $facebook->api(array( 'method' => 'fql.query','access_token' =>  $access_token, 'query' => $fql , 'callback'  => '' ));
	#debugResults($user_friends);	
  } catch (FacebookApiException $e) {
	#debugResults($e);
  }

?>

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

Shahriaz Khan on

Excellent one.. loved it

Reply
Projapoti on

Thank you very very much for such a helpful text. Its really help me a lot.
could you please tell me what should be the website URL in my apps? and for my own apps do I need permission from developer or just define permission?

Reply
thesoftwareguy on

Thanks. It feels great that the code helped you. Whenever you create a facebook app there are two things which you need to remember. i.e. the website/site url and your callback URL with the facebook both must be the same domain. Like in my case I have used http://demos.aarafacademy.com/facebook-birthday/ use your domain URL like (http://www.example.com) in which you want to apply the code. Hope that solves your problem

Reply
Sreenatha Reddy K R on

Thanks Sharukh….

Reply
a.b on

#debugResults($user_friends);
is this a commetn or what as it is havinf “#

Reply
Shahrukh Khan on

Hi a.b.
# is a single line comment in page, same like // (double backslash)
Also debugResult is just my custom function that I use to debug when I code. Just In case to check the proper output.

Reply
a.b on

okay (Y) thanku 🙂

Ritesh on

Hello Thanks for the code ,
But recantly i have faced new problem in this code .i.e.,I am not getting record when i login with my account.

Reply
Shahrukh Khan on

Check the facebook application permission.

Reply
Amin on

Thanks For the code
But i have faced friend list getting data problem in this code .i.e.,I am not getting friends list when i login with my account.

Reply
Amin on

Hello Dear,
I have apply this permission in this code.
define(“PERMISSIONS”, “user_birthday,user_friends,friends_birthday,photo_upload,user_status,publish_stream,user_photos,manage_pages”);
But not getting friend list and birthday.

Reply
Shahrukh Khan on

user friends dont require any permission, you may have some error in your code, please check my code thoroughly.

Reply
Amin on

public_profile,user_birthday,user_friends in three permissions are granted.
Any permission are granted in this code???
And your code is apply , But friends_birthday permission is not ask for the login

Reply
Shahrukh Khan on

you must have some coding error because I am able to show friends list in my demo. what part of code are you having trouble.

Reply
Nikhil on

Notice: Undefined variable: access_token in C:xampphtdocsfacebookdemoindex.php on line 19

Notice: Undefined variable: user_friends in C:xampphtdocsfacebookdemoindex.php on line 30

Reply
Shahrukh Khan on

FQL is dead and is supported no more, will have to look on graph api.

Reply
Qurban on

Thanks for the script.
$access_token is not defined in your code.
How to define it?
Thanks

Reply
Shahrukh Khan on

access code is set automatically when you login.

Reply
Mitesh on

In the latest SDK we couldn’t get this.

Reply
Shahrukh Khan on

Maybe… I haven’t seen it yet. do share more info with us if you know about it.

Reply
Sam on

I have sent you a facebook request and a message containing somethings i will like us to do together.
Please do check

Reply
Shahrukh Khan on

OK

Reply
flower on

Yes! Finally something about profile pictures.

Reply
shubham tripathi on

this code still works?

Reply
Shahrukh Khan on

I am not sure, please check the facebook docs for more info.

Reply

Leave a Reply

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