
Login With Facebook Using CodeIgniter
In this tutorial, we are going to explain how to create a Facebook login in the CodeIgniter framework using Facebook PHP SDK. Facebook login is simply an open authentication used to provide access to server data after authorizing a user through a third party.
Before you begin to integrate login with Facebook using CodeIgniter, we need to download the Facebook PHP SDK library and also need Facebook App ID and App Secret.
In this example, we are using the Facebook PHP SDK library in CodeIgniter, this library gives users permission to sign in with their existing Facebook accounts in the Codeigniter application. so we can get the user information from Facebook.
Create Facebook App
Now we need to app id facebook and App Secret for Facebook login. first, we have to create the Facebook app. so you can see the below steps.
- First, log in with your Facebook account and Go to Facebook for Developers page https://developers.facebook.com/apps/
- Click on the My apps menu at the top navigation bar and click on Create App link
- select app types
- Enter the App Display Name and App Contact Email.
- Click on the Create App button.
- In the right sidebar menu, navigate to Settings > Basic menu
- Add App Domains and select the Category of your App.
- Click the Save Changes.
- In the right sidebar menu, navigate to the Add a Product
- Select Facebook Login product.
- select the web platform.
- Enter the Site URL and Save.
- In the right sidebar menu, navigate to the Facebook Login > Settings menu.
- Add Valid OAuth Redirect URIs field
- Click the Save Changes.
- In the right sidebar menu, navigate to the Settings > Basic menu.
- get App ID and App Secret
Database Table Creation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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_url` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `link_url` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
Codeigniter configuration
application/config/autoload.php
in this config/autoload.php file, we need to load the library (database and session) and helper(URL). so you can use the below code to load the Codeigniter library and Codeigniter helper.
1 2 | $autoload['libraries'] = array('session','database'); $autoload['helper'] = array('url'); |
facebook.php
In this file, we have to set configuration variables, so we must specify the App ID, the App secret, and redirect URLs according to the Facebook application credentials.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <?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'] = 'Enter_Facebook_App_ID'; $config['facebook_app_secret'] = 'Enter_Facebook_App_Secret'; $config['facebook_login_redirect_url'] = 'facebook_login/'; $config['facebook_logout_redirect_url'] = 'facebook_login/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 SDK download for Codeigniter
first, we need to create “facebook-php-sdk” directory into the “application/third_party” directory and after go to this directory using the command prompt. download the Facebook PHP SDK library using the below command.
1 | composer require facebook/graph-sdk |
create facebook library for Codeigniter 3
application/libraries/Facebook.php
First, we must have to Include the autoload file provided by Facebook PHP SDK in this class library. after then you can easily add login with Facebook functionality using PHP SDK v5 to CodeIgniter application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | <?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 XpertPhp * @license http://xpertphp.com/license/ * @link http://xpertphp.com * @version 3.0 */ // Include the autoloader provided in the SDK require_once APPPATH .'third_party/facebook-php-sdk/vendor/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; } } ?> |
create controller in Codeigniter
application/controllers/Facebook_login.php
Go to the application/controllers directory and create a new “Facebook_login.php” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Facebook_login extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('facebook'); $this->load->model('facebook_model'); } public function index(){ $addData = array(); if($this->facebook->is_authenticated()){ $fbUserData = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email,link,gender,picture'); $addData['oauth_provider'] = 'facebook'; $addData['oauth_uid'] = !empty($fbUserData['id'])?$fbUserData['id']:'';; $addData['first_name'] = !empty($fbUserData['first_name'])?$fbUserData['first_name']:''; $addData['last_name'] = !empty($fbUserData['last_name'])?$fbUserData['last_name']:''; $addData['email'] = !empty($fbUserData['email'])?$fbUserData['email']:''; $addData['gender'] = !empty($fbUserData['gender'])?$fbUserData['gender']:''; $addData['picture_url'] = !empty($fbUserData['picture']['data']['url'])?$fbUserData['picture']['data']['url']:''; $addData['link_url'] = !empty($fbUserData['link'])?$fbUserData['link']:'https://www.facebook.com/'; $userID = $this->facebook_model->checkUser($addData); if(!empty($userID)){ $data['fbData'] = $addData; $this->session->set_userdata('fbData', $addData); }else{ $data['fbData'] = array(); } $data['logoutURL'] = $this->facebook->logout_url(); }else{ $data['authURL'] = $this->facebook->login_url(); } $this->load->view('facebook_login',$data); } public function logout() { $this->facebook->destroy_session(); $this->session->unset_userdata('fbData'); redirect('facebook'); } } ?> |
create model in codeigniter
application/models/Facebook_model.php
Go to the application/modelsdirectory and create a new “Facebook_model.php” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Facebook_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function checkUser($data = array()){ if(!empty($data)){ $this->db->select('*'); $this->db->from('users'); $this->db->where(array('oauth_provider'=>$data['oauth_provider'], 'oauth_uid'=>$data['oauth_uid'])); $query = $this->db->get(); $total_user = $query->num_rows(); if($total_user > 0){ $result = $query->row_array(); $data['updated_at'] = date("Y-m-d H:i:s"); $update = $this->db->update('users', $data, array('id' => $result['id'])); $userID = $result['id']; }else{ $data['created_at'] = date("Y-m-d H:i:s"); $data['updated_at'] = date("Y-m-d H:i:s"); $insert = $this->db->insert('users', $data); $userID = $this->db->insert_id(); } } return $userID?$userID:FALSE; } } ?> |
create view in codeigniter
application/views/facebook_login.php
Go to the application/views directory and create a new “facebook_login.php” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login With Facebook Using CodeIgniter</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div class="container"> <br /> <h2 align="center">Login With Facebook Using CodeIgniter</h2> <br /> <div class="panel panel-default"> <?php if(!empty($authURL)){ ?> <a href="<?php echo $authURL; ?>"><img src="<?php echo base_url('assets/images/facebook-login-button.png'); ?>"></a> <?php }else{ ?> <div class="panel-heading">Welcome User</div> <div class="panel-body"> <img class="img-responsive img-circle img-thumbnail" src="<?php echo $fbData['picture_url']; ?>"/> <p><b>Facebook ID:</b> <?php echo $fbData['oauth_uid']; ?></p> <p><b>Name:</b> <?php echo $fbData['first_name'].' '.$fbData['last_name']; ?></p> <p><b>Email:</b> <?php echo $fbData['email']; ?></p> <p><b>Gender:</b> <?php echo $fbData['gender']; ?></p> <p><b><a href="<?php echo $logoutURL; ?>">Logout</a></p> </div> <?php } ?> </div> </div> </body> </html> |
Read Also
Login with Facebook Account using PHP
Login With Google Account Using PHP