Sunday, May 19, 2013
Codeigniter Facebook Login Tutorial using Facebook PHP SDK
Demo
Download
Welcome to my new Codeigniter tutorial for Facebook Login. I assume that you are familar with Codeigniter framework before starting the tutorial. However, you can adopt the source code to use in native PHP application if you are not interested in CI. There is another alternative. Previously, I have published two posts related with Facebook Login. You can also refer those tutorials.
Facebook OAUTH dialog with new Graph API
AJAX Facebook Connect Demo
First you need to create a Facebook application.
Visit this link to create new app.
This is a straight-forward process.
You need to get the App ID and App Secret of your application.
First create a config file to store App ID and App Secret.
config_facebook.php
[sourcecode language="php"]
$config['appID'] = '135042780009818';
$config['appSecret'] = 'c8786043eaf9339d28568520a18b2d2f';
[/sourcecode]
Add a controller that handles Facebook login and logout.
fb.php
[sourcecode language="php"]
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
//include the facebook.php from libraries directory
require_once APPPATH . 'libraries/facebook/facebook.php';
class Fb extends CI_Controller {
public function __construct() {
parent::__construct();
$this->config->load('config_facebook');
}
public function index() {
$this->load->view('head');
$this->load->view('fb');
$this->load->view('footer');
}
public function logout() {
$signed_request_cookie = 'fbsr_' . $this->config->item('appID');
setcookie($signed_request_cookie, '', time() - 3600, "/");
$this->session->sess_destroy(); //session destroy
redirect('/fb/index', 'refresh'); //redirect to the home page
}
public function fblogin() {
$facebook = new Facebook(array(
'appId' => $this->config->item('appID'),
'secret' => $this->config->item('appSecret'),
));
// We may or may not have this data based on whether the user is logged in.
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$user = $facebook->getUser(); // Get the facebook user id
$profile = NULL;
$logout = NULL;
if ($user) {
try {
$profile = $facebook->api('/me'); //Get the facebook user profile data
$access_token = $facebook->getAccessToken();
$params = array('next' => base_url('fb/logout/'), 'access_token' => $access_token);
$logout = $facebook->getLogoutUrl($params);
} catch (FacebookApiException $e) {
error_log($e);
$user = NULL;
}
$data['user_id'] = $user;
$data['name'] = $profile['name'];
$data['logout'] = $logout;
$this->session->set_userdata($data);
redirect('/fb/test');
}
}
public function test() {
$this->load->view('test');
}
}
/* End of file fb.php */
/* Location: ./application/controllers/fb.php */
[/sourcecode]
In this tutorial, I'm using Facebook JavaScript SDK to load the oauth dialog. You need to add the App ID in following code to initiate the SDK successfully.
[sourcecode language="javascript"]
<img src="<?php echo base_url('assets/images/facebook.png');?>" id="facebook_login">
<script type="text/javascript">
window.fbAsyncInit = function() {
//Initiallize the facebook using the facebook javascript sdk
FB.init({
appId:'<?php $this->config->load('config_facebook'); echo $this->config->item('appID');?>',
cookie:true, // enable cookies to allow the server to access the session
status:true, // check login status
xfbml:true, // parse XFBML
oauth : true //enable Oauth
});
};
//Read the baseurl from the config.php file
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
//Onclick for fb login
$('#facebook_login').click(function(e) {
FB.login(function(response) {
if(response.authResponse) {
parent.location ='<?php echo base_url('fb/fblogin'); ?>'; //redirect uri after closing the facebook popup
}
},{scope: 'email,read_stream,publish_stream,user_birthday,user_location,user_work_history,user_hometown,user_photos'}); //permissions for facebook
});
</script>
[/sourcecode]
Subscribe to:
Post Comments (Atom)
How to enable CORS in Laravel 5
https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...
-
< Requirements Java Development Kit (JDK) NetBeans IDE Apache Axis 2 Apache Tomcat Server Main Topics Setup Development Environ...
-
Download Sourcecode [sourcecode language="csharp"] using System; using System.Collections.Generic; using System.Linq; using System...
i'm getting this error. can you please help?
ReplyDeleteFatal error: Call to undefined function base_url() in C:\wamp\www\CodeIgniter2\application\views\welcome_message.php on line 1 Call Stack #TimeMemoryFunctionLocation 10.0006260672{main}( )..\index.php:0 20.0032318824require_once( 'C:\wamp\www\CodeIgniter2\system\core\CodeIgniter.php' )..\index.php:202 30.03161262312call_user_func_array ( )..\CodeIgniter.php:359 40.03161262392Welcome->index( )..\CodeIgniter.php:359 50.03161262568CI_Loader->view( )..\welcome.php:22 60.03161263320CI_Loader->_ci_load( )..\Loader.php:419 70.03211289992include( 'C:\wamp\www\CodeIgniter2\application\views\welcome_message.php' )..\Loader.php:833
Hi, Please check you have loaded 'url' library. You may autoload this library.
ReplyDeleteContinuate così, bravi!
ReplyDeleteInfo Molto utile. Spero di vedere presto altri post!
ReplyDeletemmm i have a problem the image doesnt appear
ReplyDeleteThanks for your post , but how do i retrieve the Logged in user data from backend function ..
ReplyDeleteThanks Sanny.
ReplyDeleteI think you need to retrieve information from the database of the loggedin user. If this is the case first find redirect('/fb/test'); line in Fb controller. Here we redirect the verified user to Test controller. Before redirecting you can fetch user information from the database using $user_id which we already have. You can create sessions to store necessary data. This code may include in a User model. After everything is ok, you can redirect him as mentioned earlier.
logout is not happening? what to do?
ReplyDeletewhen i click on logout buttong, it redirect to facebook home page
ReplyDeleteit seems unfinished tuts. no sequences. I think you copied from another place.
ReplyDeleteHi,
ReplyDeleteNot really. Extracted this code from one of my ongoing projects at that time. So it might be incomplete and need to organize. I didn't mean rework.
libraries/facebook/facebook.php
ReplyDeletewhat content should I write in facebook.php file?
or from where should I take this file?
Hi,
ReplyDeleteplease check the source code which you can download.
You need to take part in a contest for one of the best sites online.
ReplyDeleteI most certainly will highly recommend this web site!
hey guys, can any1 help me how to insert data of user who successfully logs FB?? I can able to get info using alert but don't hav idea how to insert....
ReplyDeletei am not able to download this
ReplyDeleteHi,
ReplyDeleteSorry for the inconvenience. We 'll update links soon.
Article writing is also a fun, if you be acquainted with afterward you
ReplyDeletecan write otherwise it is complicated to write.
been working on it, hard to get data users login to insert it to database, if any tutorial register also login using facebook will big thanks :D
ReplyDeleteHello,
ReplyDeleteThanks for reading my tutorial. I'm not sure whether you 're fine with that. Anyway, I recommend you to find any recently published tutorials for this subject.
keren
ReplyDeletehello how i can use user_photos in api this is my code $user_fre = $facebook->api('/me/photos?limit=2&type=uploaded'); and get output list photos
ReplyDeletego to application/config/config.php
ReplyDeletehi,
ReplyDeletei m getting user id bt not getting any user data.
$user_profile = $facebook->api('/me');
this line is not work for me.
can not find where to download code
ReplyDeletePlease use a recently published tutorial. This might be outdated.
ReplyDeleteHi, there is no link for download. Pls send download link..
ReplyDeletethis code shows me blank page after login with fb/test link
ReplyDeletefb/test=facebook_login/fblogin both are same