So you are a PHP developer and you are trying to figure out how to integrate Facebook Login using Facebook Programming? Let me help with that.
Please note that the code in this post is not suitable for a production environment. It has been partially extracted from Codeigniter and partially formatted, but it is not ready for use in a live setting. This code is meant solely as an example.
I had to share my experience with this issue, as it was one of the most frustrating things I have faced in a while. After searching online, I discovered that many others have faced similar problems with Facebook registration and login. I hope to save others the stress and headache of figuring it out for themselves, as I spent two to three days experimenting and understanding how it works. Through trial and error, I have gained a thorough understanding of the process and figured out some key points.
Step One: Create App
Creating a Facebook account (if you don’t already have one) and logging in. At the bottom of the page, you will see a “Developers” link. Click on that link and then on “My Apps” at the top right corner of the screen. To set up a new app, click on “Set Up New App” and follow the instructions. Be sure to enter your website address as the return URL. This is crucial and make sure to follow the instructions carefully.
An unverified Facebook account may prevent you from accessing the create app screen. Use your mobile number or credit card to verify your account. Then you can proceed.
Once you have created the app, make a note of the APP Id, Secret Key, and API Key from the app settings. Also, remember the site URL and domain. Most of the time, issues with setting up arise from incorrect basic information.
Step Two: Registration
You need to enable users to link their account on your site with their Facebook account. This enables the automatic login through Facebook. An initial connection between Facebook and your system records the Facebook User ID. This allows your system to match up user accounts during the login process. The login process is simple.
You can set this up in different ways. I used the Iframe method and it worked well for me. Add the following code to your registration form. You have a standard registration option and the Facebook Connect code. Both standard registration and Facebook integration allow easy login.
[code]
[/code]
To set up the user interface (UI) for Facebook integration, follow these steps:
- Replace APP_ID with the ID of your application, which was explained earlier.
- Replace REDIRECT_URL with the URL of the page you want the script to send the data to. Note: The redirect URL must contain the same base URL that was configured when creating the app. For example, if your website is http://www.whatever.com and the page to process the data is process_facebook.php, then the redirect URL should be http://www.whatever.com/process_facebook.php.
To process the registration, do the following:
- Assume the file for processing the registration is process_facebook.php.
- Include the code in process_facebook.php. Note: If using the same setup as the example, this file should be in the root folder.
[code]
define(‘FACEBOOK_APP_ID’, ‘APPID’);
define(‘FACEBOOK_SECRET’, ‘SECRETKEY’);
if ($_REQUEST) {
$response = parse_signed_request($_REQUEST[‘signed_request’], FACEBOOK_SECRET);
$user_data = array();
$user_data[‘facebook_userid’] = $response[‘user_id’];
$user_data[‘facebook_connect’] = 1;
$user_data[’email’] = $response[‘registration’][’email’];
$name = explode(” “, $response[‘registration’][‘name’]);
$user_data[‘first_name’] = $name[0];
$user_data[‘last_name’] = $name[count($name)-1];
$sql = “INSERT INTO user_information (first_name, last_name, email, facebook_userid, facebook_connect) VALUES (‘” . $user_data[‘first_name’] . “‘,'” . $user_data[‘last_name’] . “‘,'” . $user_data[’email’] . “‘,'” . $user_data[‘facebook_userid’] . “‘,'” . $user_data[‘facebook_connect’] . “‘)”;
if (mysql_query($sql)) {
// Setup success message and redirect
}else {
// Setup failed message and redirect
}
} else {
// Setup error message that request was empty
}
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode(‘.’, $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data[‘algorithm’]) !== ‘HMAC-SHA256’) {
error_log(‘Unknown algorithm. Expected HMAC-SHA256’);
return null;
}
// check sig
$expected_sig = hash_hmac(‘sha256’, $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log(‘Bad Signed JSON signature!’);
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, ‘-_’, ‘+/’));
}
[/code]
First replace APPID with the application ID, then replace SECRETKEY with the application secret key. Both of these can be found inside the Facebook settings which I have explained earlier. Those two functions were ones that I have taken from Facebook examples. These handle what is needed to decode the operation, and beats having to right it all from scratch.
Step Three: Login
The Login script is the last and hardest step. It has 2-3 steps and is complicated. The first step handles the user login/register or other needs. A lot of things happen in this step. The user logs into Facebook if they are not already. If they are, it skips this step. Then, it checks if the user authorized this application to access their information. It prompts them to do so if they haven’t. If they have, it skips this step. The front end flow is below:
- User clicks link.
- If logged in then great. If not, then prompt for facebook login.
- If authorized for this app then great, if not them prompt for authorization from user
- If they decline auth, then it redirects them to fail page. If they approve or have already approved it handles Login automatically
behind the scenes
That is the general flow of this entire situation. Now let’s see how all of this runs on the backend.
The first thing we need is to verify whether or not the user is currently logged into facebook, if not we need to require them to login via facebook. Facebook actually handles all of this for us. We just need to automatically point the users in the right direction. This is where we actually create our facebook link that says “Login Via Facebook” or “Connect Via Facebook” or whatever you want. The code is below:
[code]
Facebook Connect
[/code]
This is where the important step comes in. The easy part is your app id. Just replace that with your app id. Now for the redirect URL. You need to put in the URL to the file that is going to process all of this. The thing is, this has to be a filename that you remember. Since we have to use this a few times…
Once they do this, it will handle their login, and authorization and everything else.
The next step is to deal with the processing using the following code (all found on facebook_connect.php in my script). So if your
redirect url is http://www.website.com/facebook_connect.php then that is where all of this code is going to go. In facebook_connect.php in your root folder on your web server.
[code]
$code = $_REQUEST[‘code’];
$url = ‘https://graph.facebook.com/oauth/access_token?client_id=APPID&redirect_uri=REDIRECTURL&scope=offline_access&client_secret=APPSECRETKEY&code=’ . $code;
$access_code = file_get_contents($url);
$url = ‘https://graph.facebook.com/me?’ . $access_code;
$data = json_decode(file_get_contents($url));
$sql = “SELECT * FROM user_information WHERE facebook_userid = ‘” . mysql_real_escape_string($data->id) . “‘”;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$user_id = $row[‘user_id’];
}
header(‘Location: http://www.cheetahseat.com/index.php/fblogin/autologin/’ . $user_id);
?>
[/code]
That’s all there is too it. Replace the app id, and secret key with your unique information from the facebook app you created. Now here is the catch…the return url here, HAS to be the exact same as it was on the previous link. In short, EVERYTHING has to happen on this one page. If you try to do ONE step of the process with a different return URL it will not work. Make sure the return URL on this page is the
EXACT same as the one you provided in the original anchor link. Or it will not work. It’ll return a strange error like cannot verify URL or something. That is pretty much everything.
Codeigniter Integration
To set up Facebook OAuth in CodeIgniter, an extra layer of work is needed as the process can be difficult. I found a simple solution that works well, but you may want to add more security to the login process for added protection.
Create a file named “facebook_connect.php” outside of the CodeIgniter directory. In one of your CodeIgniter views, have an anchor link that points to “www.website.com/facebook_connect.php“. All the code needed for the OAuth process should be in this file. To access the CodeIgniter database, include the following code at the top of the page.
[code]
define(‘BASEPATH’, ‘/system/’);
require_once(‘system/application/config/database.php’);
mysql_connect($db[‘default’][‘hostname’], $db[‘default’][‘username’], $db[‘default’][‘password’]);
mysql_select_db($db[‘default’][‘database’]);
[/code]
This code gives you full access to all MySQL functionality using standard MySQL functions, and maintains a connection to the CodeIgniter database. This saves you time by eliminating the need to run everything through a separate database. To ensure security in CodeIgniter, take a few precautions. Redirect users to a unique URL that is not easily guessable, pass the Facebook user ID, and use it to connect the user to the database and match them with your user ID. This adds extra security as someone would need to guess a Facebook user’s ID to gain access to the system. Finally, perform a standard login and redirect the user back to the homepage while they are logged in.
Closing
This guide has my experiences with Facebook authentication. I might improve it later with new ideas. It took 18 hours in 3-4 days to get it right. The main challenge was using two separate files (facebook_connect.php and facebook_connect2.php). They had to be the same. I hope this guide helped and good luck with your implementation.
The PHP documentation can be found here.
Other blog posts on my site that are archived can be found here.
Random note: This post was written in 2012 and some of the information may be outdated. Facebook Login is a feature that allows users to authenticate themselves with their Facebook accounts on apps and websites. Facebook Login using Python has different methods. One is using Selenium. Another is using Facebook’s SDK. Facebook Login also works with existing login systems. Verify the email address linked to the user’s Facebook account for this.