Facebook Login Integration is the most used feature of today’s web application. Login with Facebook feature helps the user to log into the web application without prior account registration. This means that your web application will get more users/customers. We’ve already published Login with Facebook using PHP tutorial that helps to implement Facebook login in PHP application. In this tutorial, we’re going to explain how to integrate Facebook Login in CodeIgniter framework using Facebook PHP SDK and Graph API.
In the example CodeIgniter Facebook OAuth application, we will implement user authentication with Facebook PHP Graph SDK v5.x and store the user’s profile information in the MySQL database. Before you begin to integrate Facebook Login in CodeIgniter, take a look at the files structure of the application.
codeigniter_facebook_login/ ├── application/ │ ├── config/ │ │ └── facebook.php │ ├── controllers/ │ │ └── User_authentication.php │ ├── libraries/ │ │ └── Facebook.php │ ├── models/ │ │ └── User.php │ ├── third_party/ │ │ └── facebook-php-graph-sdk/ │ └── views/ │ └── user_authentication/ │ └── index.php └── assets/ ├── css/ │ └── style.php └── images/ └── fb-login-btn.png
To getting started to implement Facebook login in CodeIgniter 3 using PHP SDK, you need to create a Facebook App in the Facebook developers panel and get the App ID and App Secret. The App ID and App Secret are required to connect with Facebook OAuth API and Graph API through PHP SDK. Go through the below tutorial for a step-by-step guide to create Facebook App, App ID, and App Secret.
Once your Facebook app creation is completed, copy the App ID and App Secret for later use in the script.
Note that: The App ID and App secret need to be specified in the Facebook API configuration file. Also, the Valid OAuth Redirect URIs must be matched with the user authentication controller (ex: https://www.codexworld.com/user_authentication/
).
To store the user’s Facebook profile data, a table needs to be created in the database. The following SQL creates an users
table with some basic fields in the MySQL database.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oauth_provider` enum('facebook','google','twitter','') COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`link` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
autoload.php
In the config/autoload.php
file, define the commonly used library (database and session) and helper (url) to load automatically on every request.
$autoload['libraries'] = array('session','database'); $autoload['helper'] = array('url');
facebook.php
In the config/facebook.php
file, the Facebook App and API configurations are defined. Specify the App ID, App Secret and Redirect URL according to your Facebook App credentials.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | Facebook API Configuration | ------------------------------------------------------------------- | | To get an facebook app details you have to create a Facebook app | at Facebook developers panel (https://developers.facebook.com) | | facebook_app_id string Your Facebook App ID. | facebook_app_secret string Your Facebook App Secret. | facebook_login_redirect_url string URL to redirect back to after login. (do not include base URL) | facebook_logout_redirect_url string URL to redirect back to after logout. (do not include base URL) | facebook_login_type string Set login type. (web, js, canvas) | facebook_permissions array Your required permissions. | facebook_graph_version string Specify Facebook Graph version. Eg v3.2 | facebook_auth_on_load boolean Set to TRUE to check for valid access token on every page load. */ $config['facebook_app_id'] = 'Insert_Facebook_App_ID'; $config['facebook_app_secret'] = 'Insert_Facebook_App_Secret'; $config['facebook_login_redirect_url'] = 'user_authentication/'; $config['facebook_logout_redirect_url'] = 'user_authentication/logout'; $config['facebook_login_type'] = 'web'; $config['facebook_permissions'] = array('email'); $config['facebook_graph_version'] = 'v3.2'; $config['facebook_auth_on_load'] = TRUE;
facebook-php-graph-sdk/
The facebook-php-graph-sdk/ directory contains the latest version (v5) of Facebook SDK for PHP. Facebook PHP SDK is used to connect with the Facebook Graph API and integrate login system with Facebook.
Note that: The Facebook PHP SDK needs to be placed in the third_party/
directory of your CodeIgniter application. You don’t need to download the Facebook PHP SDK library separately, all the required files are included in the source code.
Facebook.php
The Facebook OAuth library helps to integrate Facebook PHP SDK v5 in CodeIgniter 3.x application. Using this Facebook class, you can easily add the login with Facebook functionality using PHP SDK v5 to the CodeIgniter application.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Facebook PHP SDK v5 for CodeIgniter 3.x
*
* Library for Facebook PHP SDK v5. It helps the user to login with their Facebook account
* in CodeIgniter application.
*
* This library requires the Facebook PHP SDK v5 and it should be placed in libraries folder.
*
* It also requires social configuration file and it should be placed in the config directory.
*
* @package CodeIgniter
* @category Libraries
* @author CodexWorld
* @license http://www.codexworld.com/license/
* @link http://www.codexworld.com
* @version 3.0
*/
// Include the autoloader provided in the SDK
require_once APPPATH .'third_party/facebook-php-graph-sdk/autoload.php';
use Facebook\Facebook as FB;
use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Helpers\FacebookJavaScriptHelper;
use Facebook\Helpers\FacebookRedirectLoginHelper;
Class Facebook
{
/**
* @var FB
*/
private $fb;
/**
* @var FacebookRedirectLoginHelper|FacebookJavaScriptHelper
*/
private $helper;
/**
* Facebook constructor.
*/
public function __construct(){
// Load fb config
$this->load->config('facebook');
// Load required libraries and helpers
$this->load->library('session');
$this->load->helper('url');
if (!isset($this->fb)){
$this->fb = new FB([
'app_id' => $this->config->item('facebook_app_id'),
'app_secret' => $this->config->item('facebook_app_secret'),
'default_graph_version' => $this->config->item('facebook_graph_version')
]);
}
// Load correct helper depending on login type
// set in the config file
switch ($this->config->item('facebook_login_type')){
case 'js':
$this->helper = $this->fb->getJavaScriptHelper();
break;
case 'canvas':
$this->helper = $this->fb->getCanvasHelper();
break;
case 'page_tab':
$this->helper = $this->fb->getPageTabHelper();
break;
case 'web':
$this->helper = $this->fb->getRedirectLoginHelper();
break;
}
if ($this->config->item('facebook_auth_on_load') === TRUE){
// Try and authenticate the user right away (get valid access token)
$this->authenticate();
}
}
/**
* @return FB
*/
public function object(){
return $this->fb;
}
/**
* Check whether the user is logged in.
* by access token
*
* @return mixed|boolean
*/
public function is_authenticated(){
$access_token = $this->authenticate();
if(isset($access_token)){
return $access_token;
}
return false;
}
/**
* Do Graph request
*
* @param $method
* @param $endpoint
* @param array $params
* @param null $access_token
*
* @return array
*/
public function request($method, $endpoint, $params = [], $access_token = null){
try{
$response = $this->fb->{strtolower($method)}($endpoint, $params, $access_token);
return $response->getDecodedBody();
}catch(FacebookResponseException $e){
return $this->logError($e->getCode(), $e->getMessage());
}catch (FacebookSDKException $e){
return $this->logError($e->getCode(), $e->getMessage());
}
}
/**
* Generate Facebook login url for web
*
* @return string
*/
public function login_url(){
// Login type must be web, else return empty string
if($this->config->item('facebook_login_type') != 'web'){
return '';
}
// Get login url
return $this->helper->getLoginUrl(
base_url() . $this->config->item('facebook_login_redirect_url'),
$this->config->item('facebook_permissions')
);
}
/**
* Generate Facebook logout url for web
*
* @return string
*/
public function logout_url(){
// Login type must be web, else return empty string
if($this->config->item('facebook_login_type') != 'web'){
return '';
}
// Get logout url
return $this->helper->getLogoutUrl(
$this->get_access_token(),
base_url() . $this->config->item('facebook_logout_redirect_url')
);
}
/**
* Destroy local Facebook session
*/
public function destroy_session(){
$this->session->unset_userdata('fb_access_token');
}
/**
* Get a new access token from Facebook
*
* @return array|AccessToken|null|object|void
*/
private function authenticate(){
$access_token = $this->get_access_token();
if($access_token && $this->get_expire_time() > (time() + 30) || $access_token && !$this->get_expire_time()){
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
// If we did not have a stored access token or if it has expired, try get a new access token
if(!$access_token){
try{
$access_token = $this->helper->getAccessToken();
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e->getMessage());
return null;
}
// If we got a session we need to exchange it for a long lived session.
if(isset($access_token)){
$access_token = $this->long_lived_token($access_token);
$this->set_expire_time($access_token->getExpiresAt());
$this->set_access_token($access_token);
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
}
// Collect errors if any when using web redirect based login
if($this->config->item('facebook_login_type') === 'web'){
if($this->helper->getError()){
// Collect error data
$error = array(
'error' => $this->helper->getError(),
'error_code' => $this->helper->getErrorCode(),
'error_reason' => $this->helper->getErrorReason(),
'error_description' => $this->helper->getErrorDescription()
);
return $error;
}
}
return $access_token;
}
/**
* Exchange short lived token for a long lived token
*
* @param AccessToken $access_token
*
* @return AccessToken|null
*/
private function long_lived_token(AccessToken $access_token){
if(!$access_token->isLongLived()){
$oauth2_client = $this->fb->getOAuth2Client();
try{
return $oauth2_client->getLongLivedAccessToken($access_token);
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e->getMessage());
return null;
}
}
return $access_token;
}
/**
* Get stored access token
*
* @return mixed
*/
private function get_access_token(){
return $this->session->userdata('fb_access_token');
}
/**
* Store access token
*
* @param AccessToken $access_token
*/
private function set_access_token(AccessToken $access_token){
$this->session->set_userdata('fb_access_token', $access_token->getValue());
}
/**
* @return mixed
*/
private function get_expire_time(){
return $this->session->userdata('fb_expire');
}
/**
* @param DateTime $time
*/
private function set_expire_time(DateTime $time = null){
if ($time) {
$this->session->set_userdata('fb_expire', $time->getTimestamp());
}
}
/**
* @param $code
* @param $message
*
* @return array
*/
private function logError($code, $message){
log_message('error', '[FACEBOOK PHP SDK] code: ' . $code.' | message: '.$message);
return ['error' => $code, 'message' => $message];
}
/**
* Enables the use of CI super-global without having to define an extra variable.
*
* @param $var
*
* @return mixed
*/
public function __get($var){
return get_instance()->$var;
}
}
User_authentication.php
The User_Authentication controller handles the Facebook API authentication process using PHP SDK and Graph API.
login_url()
method of the Facebook library.request()
method of the Facebook library.checkUser()
function of the User model.logout_url()
method of the Facebook library.<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller {
function __construct() {
parent::__construct();
// Load facebook oauth library
$this->load->library('facebook');
// Load user model
$this->load->model('user');
}
public function index(){
$userData = array();
// Authenticate user with facebook
if($this->facebook->is_authenticated()){
// Get user info from facebook
$fbUser = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email,link,gender,picture');
// Preparing data for database insertion
$userData['oauth_provider'] = 'facebook';
$userData['oauth_uid'] = !empty($fbUser['id'])?$fbUser['id']:'';;
$userData['first_name'] = !empty($fbUser['first_name'])?$fbUser['first_name']:'';
$userData['last_name'] = !empty($fbUser['last_name'])?$fbUser['last_name']:'';
$userData['email'] = !empty($fbUser['email'])?$fbUser['email']:'';
$userData['gender'] = !empty($fbUser['gender'])?$fbUser['gender']:'';
$userData['picture'] = !empty($fbUser['picture']['data']['url'])?$fbUser['picture']['data']['url']:'';
$userData['link'] = !empty($fbUser['link'])?$fbUser['link']:'https://www.facebook.com/';
// Insert or update user data to the database
$userID = $this->user->checkUser($userData);
// Check user data insert or update status
if(!empty($userID)){
$data['userData'] = $userData;
// Store the user profile info into session
$this->session->set_userdata('userData', $userData);
}else{
$data['userData'] = array();
}
// Facebook logout URL
$data['logoutURL'] = $this->facebook->logout_url();
}else{
// Facebook authentication url
$data['authURL'] = $this->facebook->login_url();
}
// Load login/profile view
$this->load->view('user_authentication/index',$data);
}
public function logout() {
// Remove local Facebook session
$this->facebook->destroy_session();
// Remove user data from session
$this->session->unset_userdata('userData');
// Redirect to login page
redirect('user_authentication');
}
}
User.php
The User model handles the database related operations (insert and update).
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Model { function __construct() { $this->tableName = 'users'; $this->primaryKey = 'id'; } /* * Insert / Update facebook profile data into the database * @param array the data for inserting into the table */ public function checkUser($userData = array()){ if(!empty($userData)){ //check whether user data already exists in database with same oauth info $this->db->select($this->primaryKey); $this->db->from($this->tableName); $this->db->where(array('oauth_provider'=>$userData['oauth_provider'], 'oauth_uid'=>$userData['oauth_uid'])); $prevQuery = $this->db->get(); $prevCheck = $prevQuery->num_rows(); if($prevCheck > 0){ $prevResult = $prevQuery->row_array(); //update user data $userData['modified'] = date("Y-m-d H:i:s"); $update = $this->db->update($this->tableName, $userData, array('id' => $prevResult['id'])); //get user ID $userID = $prevResult['id']; }else{ //insert user data $userData['created'] = date("Y-m-d H:i:s"); $userData['modified'] = date("Y-m-d H:i:s"); $insert = $this->db->insert($this->tableName, $userData); //get user ID $userID = $this->db->insert_id(); } } //return user ID return $userID?$userID:FALSE; } }
user_authentication/index.php
If the user already logged in with their Facebook account, the profile details are displayed. Otherwise, Sign-in with Facebook button is shown to the user.
<!-- Display login button / Facebook profile information -->
<?php if(!empty($authURL)){ ?>
<h2>CodeIgniter Facebook Login</h2>
<a href="<?php echo $authURL; ?>"><img src="<?php echo base_url('assets/images/fb-login-btn.png'); ?>"></a>
<?php }else{ ?>
<h2>Facebook Profile Details</h2>
<div class="ac-data">
<img src="<?php echo $userData['picture']; ?>"/>
<p><b>Facebook ID:</b> <?php echo $userData['oauth_uid']; ?></p>
<p><b>Name:</b> <?php echo $userData['first_name'].' '.$userData['last_name']; ?></p>
<p><b>Email:</b> <?php echo $userData['email']; ?></p>
<p><b>Gender:</b> <?php echo $userData['gender']; ?></p>
<p><b>Logged in with:</b> Facebook</p>
<p><b>Profile Link:</b> <a href="<?php echo $userData['link']; ?>" target="_blank">Click to visit Facebook page</a></p>
<p><b>Logout from <a href="<?php echo $logoutURL; ?>">Facebook</a></p>
</div>
<?php } ?>
After the code implementation, now it’s time to test the Facebook Login in CodeIgniter application. Open the application OAuth URL (https://www.example.com/user_authentication/
) in the browser.
Login with Facebook without Page Refresh using JavaScript SDK
We have tried to make the Facebook login integration easier for the CodeIgniter web application. Hope! you can easily implement Facebook login system in CodeIgniter using our example code. The example code uses the latest version of Facebook SDK, so, Facebook PHP SDK v5 library is required. You don’t need to download the SDK library separately, all the required files are included in our source code (including the PHP SDK v5 for CodeIgniter).
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Awesome, this method is still working till rite now!
Thanks, you make me save my time
nice …. your work is awesome…..<3
It’s works like a charm, thank you!
Where can i get sdk file?
Download the source code.
My CI Version 3.1.4 , i am using facebook-php-sdk 4.x. It doesn’t work. How to Download facebook-php-sdk 5.x
Download the source code, it contains all the required files including Facebook PHP SDK v5.
I´m getting the error “URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings.”
This error occurs because the specified Redirect URL in the Valid OAuth Redirect URIs is not valid. You need to check whether the specified redirect URL in the script is matched with Facebook App settings.
I have a question where should I save this facebook.php file ? I mean in which directory , thanks please answer urgently
Hi,
Great library. Works so far.
My question is that the profile picture is very small/bad quality.
How can I improve this?
Regards,
Jaco
Follow this guide to get large size profile picture in Facebook PHP SDK – https://www.codexworld.com/how-to/get-large-size-profile-picture-in-facebook-php-sdk/
how to change my access token
well. it is my fault. “pure” domain name is needed
i bought the source code recently , but it does not work in localhost. or other host it shows: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
=== >i did add the OAuth white list. do you have any suggestion? thx.
Thanks for purchasing our script. It will work on localhost and other hosts. Use localhost.com for localhost and use the entire domain name (codexworld.com) for other hosts.
How to get users Phone / Mobile number
You’r to good. Its really nice.
how can i get Facebook PHP SDK without pay.
Download the source code, it contains the Facebook PHP SDK.
This tutorial is very nice and explain with step by step & video is super in youtube .keep it up codexworld. one thing am big fan codexworld thank you 🙂
how the way to use random _bytes() function?
Hi, thank you for awsome tutorial, but I have a problem implementing, I got error message:
A PHP Error was encountered
Severity: 8192
Message: Function mcrypt_create_iv() is deprecated
Filename: PseudoRandomString/McryptPseudoRandomStringGenerator.php
I used php version 7.1.4, how to fix this error?
thank you
The
mcrypt_create_iv()
function is deprecated in PHP 7, userandom_bytes()
function instead inPseudoRandomString/McryptPseudoRandomStringGenerator.php
file.Great Job!, Thanks
Hi ,, thanks for his tutorial about facebook login on codeigniter. But here I am having a little problem where my facebook application can not be used as in your tutorial. Setting how i can use facebook login on network localhost. Error as in the following image links. https://prnt.sc/f9pry2. Please help me to solve this problem. thank you
Remove the Valid OAuth redirect URIs, it’s not needed. Follow these simple steps to create a facebook app for localhost – https://www.codexworld.com/create-facebook-app-id-app-secret/
can you provide link where i can faind facebook-php-sdk v5.
The Facebook PHP SDK and all the required files are included in the source code.
This is awesome
Thanks for this awesome code. It works fine for me saves soo much time.Thanks to the codex team
Hi,
That’s what I need, Awesome code working fine with latest updation in facebook library. Thanks to codex team for this awesome code.
Thanks 🙂
hai, im new to code igniter, and thank you for your tutorial. but i have a problem when extract the source to my codeigniter folder in localhost. when i check, i get 0 return for this script : $fbuser = $facebook->getUser();
i have followed the instruction in redme files, and i dont edit the script of your tutorial. i just edit the database setting, thats all..
so, can you tell me is there anything else to edit or set? thank you very much
We’ve updated our tutorial with Facebook PHP SDK v5. Please follow the updated tutorial and download the latest version of source code.
The redirect_uri URL must be absolute…. please tell me what is this error for ?
The specified Redirect URL in the script must match with the Site URL of your Facebook App.
Thanks CODEX TEAM ! It worked smooth 😀
Great tutorial. but could you do the same thing with the current facebook php sdk 5?
@John We’ll try to publish this tutorial with PHP SDK v5 soon.
//$redirectUrl = base_url() . ‘user_authentication/’;
$redirectUrl = ‘http://localhost/smartlogin/user_authentication/’;
The commented line was working so i came up with the 2nd line of code, and ooppsss ulalah its now working all fine , Thanks alot Devs
perfect , any help on how to use it on my pc localhost?
This is a awesome tutorial. perfect working! 🙂
Thank you codexworld…i have learned lot’s of things from this tutorials
Tnx so much, it works nice, but when I log out the session does not destroy ! how can i solve this problem?!!
Awesome work guys. But I am facing a problem when I log out. The session does not get destroyed automatically when I click on the logout link. I have to literally open my facebook account tab and get logged out. What could be the possible reason?
PS: I am new to codeigniter 😀
This is awesome Guys try it out… COdexWorld you really done amazing Jobs. . .
NEW REQUEST: ” Codeigniter Newletter Subscription and Send Newletter to the Subscriber”