In a series of tutorials I will be showing you how to do different things from using the Facebook API to PHP Functions and more.
In this tutorial I will be showing you how to integrate the Facebook platform in to your own website using the Facebook PHP API and how
you can access users information to store in your own database, or as I use it to help auto complete sign up forms.
Facebook's platform is quite menacing to look at and for the average user, it can be also confusing. So I will talk
you through the steps of how to use Facebook on your own website.
If you want to learn some much easier ways to intergate your website with Facebook you can visit here:
http://developers.facebook.com/docs/samples/ , here you can learn to add like buttons and other ways of intergrating with Facebook.
We will be working directly with the PHP API, you can download the facebook.php file here. Go to the src folder and
get the facebook.php file. What you will need is a little knowledge of PHP and MySQL for this tutorial.
Resources:
Facebook Developer Account / Application
Facebook API Key
Facebook Secert Key
Facebook API php file //Do not edit anything in this file.
PHP
MySQL Database
So if you have not already, go and create a new developer account: http://www.facebook.com/developers/ and click 'Set Up New App'
Name your app whatever you wish and agree to the terms and conditions. Fill out all the information if you wish, but for now this is not
really that important. But you might want to add your website URL.
What we need is on the tab Web Site. You will see your Application ID and Application Secret, also known as your OAuth client_id and OAuth
client_secret. Save these in notepad or keep the browsed page handy for when we start our coding.
Lets get coding.
Our app needs to start with this:
<?php
// Awesome FB APP
//
// Name: MyAPP
//
require_once 'facebook.php';// this line calls our facebook.php file
//that is the core of PHP facebook API
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET',
'cookie' => true,
)); // all we are doing is creating an array for facebook to use with our
//app id and app secret in and setting the cookie to true
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
} // this code is saying if the session to the app is created use the
// $me as a selector for the information or die
?>
that is all you need to create a connection / call to the API, it is that simple, now for us to have a little bit more fun with our app. Now
every item returned in the Facebook API will be in an ARRAY format. Arrays are a collection of data.
Buttons for signing up / in:
Collecting data from a person is limited by default and you can view the full list of requests here: http://developers.facebook.com/docs/reference/api/
But for this application we will only be taking First Name, Second Name and Email Address, the first two objects we want are sent to us by
default when the user signs up to our website, but requesting an email means we have to make a small change to our call button.
<fb:login-button perms='email'> Connect</fb:login-button> //perms is premissions
//we are asking the user to agree with to allow our app to work
<div id='fb-root'></div>
<script src='http://connect.facebook.net/en_US/all.js'></script>
<script>
FB.init({
appId:'YOUR APP ID', cookie:true,
status:true, xfbml:true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
</script>
The rest of the above code is standard for any facebook call button. This button will allow users to our website to access our app and let
us have certain information the user is willing to share with us. So how do we now get that information from our user? When a user agrees to
use our website via the app, Facebook creates a session on our website. Now we dont need this to read our information we want to this will
become very useful for when we need to fill out a form.
this is how we get the users information:
<?=$me['first_name']?>
<?=$me['last_name']?>
<?=$me['email']?>
here we are using php short tags to echo our new users first name. Remember when we connected to the Facebook API we created the variable
$me which in turns connects to the Facebook API selects the users first name from the array and displays it. Simple when you know how.
*Remember to use this exactly as I have written it. Facebook only creates the Array as first_name, FirstName or firstname will not work.
What we need to do now is create a sign up page for our own website which we can now use these details from Facebook to fill out our boxes.
<form action='facebooksignup.php' method='post'>
<fieldset class='field_name'>
<label>First Name *</label>
<input class='name' name='first_name' type='text' value='<? if ($facebook->getSession())
{echo $me['first_name'];}else{echo'First Name';} ?>' />
</fieldset>
<fieldset class='field_name'>
<label>Last Name *</label>
<input class='name' name='last_name' type='text' value='<? if ($facebook->getSession())
{echo $me['last_name'];}else{echo'Last Name';} ?>' />
</fieldset>
<fieldset>
<label>Email Address *</label>
<input name='email' type='text' value='<? if ($facebook->getSession()) {
echo $me['email'];}else{echo'email address';} ?>' />
</fieldset>
<fieldset>
<input name='submit' type='submit' value='submit' />
</fieldset>
</form>
What we have above is a simple sign up form. As a value you can see we are using an IF statement to check if Facebook has created a session
on our website for the user and if it has to echo out the details we have asked for. The else statement is incase the session is not created
to either leave blank or say something else.
** note you can add more fields to this like address, telephone etc that is up to you and what
information you require for your website.
All we need to do now is to take that information entered in to the form and insert it in to a database. Now I am not going to code the full
adding to the database, adding security to this page is up to you. I will only show you how to insert our fields in to the database.
Now in our form we used the method 'post'. This is important to remember as for coding this page we will be using this request to collect
our information.
<?
session_start(); // i start most if not all pages with this
$host = 'LOCALHOST'; // host name
$username = 'USERNAME' ;//username
$pass = 'PASSWORD' ; //password
$dbname = 'DATABASENAME'; // Database Name
$conn = mysql_connect($host, $username, $pass) or die(mysql_error());
if ($conn)
{
mysql_select_db($dbname) or die(mysql_error());
}
else
{
echo 'Connection failed.';
} // The above code connects to your database or errors if it cannot connect.
// Again this is simple, security is your own priority.
//here you could add checks for any empty fields using (!($_POST['first_name']))
$first_name = $_POST['first_name']; // this line will collect our information from
//the field in our form that has the facebook first_name in it.
$last_name = $_POST['last_name']; // same as above
$email = $_POST ['email']; //same as above
$query = mysql_query('INSERT INTO Facebook (first_name, last_name, email) VALUES
('$first_name','$last_name','$email')') or die(mysql_error());
// The query will insert our fields in to the database as the above line shows,
// make sure your database table headers are exactly correctotherwise this will not work
// You can now either send an email or if you wanted header to a new page. This is up
//to you. Tutorials on google will show you how to do thispart.
?>
Here is the tutorial in full and how I would use it 'facebook_signup.php':
<?php
// Awesome FB APP
//
// Name: MyAPP
//
require_once 'facebook.php';// this line calls our facebook.php file that is the
//core of PHP facebook API
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET',
'cookie' => true,
)); // all we are doing is creating an array for facebook to use with our
//app id and app secret in and setting the cookie to true
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
} // this code is saying if the session to the app is created use
//the $me as a selector for the information or die
?>
<!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>Facebook APP</title>
</head>
<body>
<? if ($facebook->getSession()) { ?>
<form action='signup.php' method='post'>
<fieldset class='field_name'>
<label>First Name</label>
<input class='name' name='first_name' type='text' value='<? if ($facebook->getSession())
{echo $me['first_name'];}else{echo'First Name';} ?>' />
</fieldset>
<fieldset class='field_name'>
<label>Last Name</label>
<input class='name' name='last_name' type='text' value='<? if ($facebook->getSession())
{echo $me['last_name'];}else{echo'Last Name';} ?>' />
</fieldset>
<fieldset>
<label>Email Address</label>
<input name='email' type='text' value='<? if ($facebook->getSession())
{echo $me['email'];}else{echo'email address';} ?>' />
</fieldset>
<fieldset>
<input name='submit' type='submit' value='submit' />
</fieldset>
</form>
<? } else {
?>
<p>Sign up with Facebook <fb:login-button perms='email'> Connect</fb:login-button>
It only takes a few seconds</p>
<div id='fb-root'></div>
<script src='http://connect.facebook.net/en_US/all.js'></script>
<script>
FB.init({
appId:'YOUR APP ID', cookie:true,
status:true, xfbml:true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload(); //will reload your page you are on
});
</script>
<? }
?>
</body>
</html>
Next the database connect code 'signup.php':
<?
session_start(); // i start most if not all pages with this depending on what Im using it for.
$host = 'LOCALHOST'; // host name OR IP
$username = 'USERNAME' ;//username
$pass = 'PASSWORD' ; //password
$dbname = 'DATABASENAME'; // Database Name
$conn = mysql_connect($host, $username, $pass) or die(mysql_error());
if ($conn)
{
mysql_select_db($dbname) or die(mysql_error());
}
else
{
echo 'Connection failed.';
} // The above code connects to your database or errors if it cannot connect.
// Again this is simple, security is your own priority.
//here you could add checks for any empty fields using (!($_POST['first_name']))
$first_name = $_POST['first_name']; // this line will collect our information from the
// field in our form that has the facebook first_name in it.
$last_name = $_POST['last_name']; // same as above
$email = $_POST ['email']; //same as above
$query = mysql_query('INSERT INTO Facebook (first_name, last_name, email) VALUES
('$first_name','$last_name','$email')') or die(mysql_error());
// The query will insert our fields in to the database as the above line shows, make
//sure your database table headers are exactly correct otherwise this will not work
// You can now either send an email or if you wanted header to a new page. This is
//up to you. Tutorials on google will show you how to do this part
if($query){
header('location: home.html');
}else {
echo 'error adding to database';
}
?>
Conclusion:
We have now built a fully functioning web application using the Facebook PHP API. We have checked to see if a session is active, if not
display the button to get the user to register with your app. Once registed they can complete a sign up form for your website, which adds
the users details to a database.
I understand that there are other more secure ways to do this tutorial, but this tutorial is for beginners wanting to learn now to call the API and
use it to store information in a database.
There are many other ways to use this tutorial, you know have the basic knowledge you need to connect to facebook and collect information.
You can download the zip of these files here: Download
Was this tutorial helpful? Leave a comment.
Author: Rob Cullen / Posted: 30-03-2011