Showing posts with label facebook login. Show all posts
Showing posts with label facebook login. Show all posts

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.

New App





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]

Friday, June 8, 2012

Facebook OAUTH dialog with new Graph API

Demo Download

You need a PHP enabled real server to test this application.

Login to your Facebook account and add a developer application
Facebook developers
tips : App Domain should be in myDomain.com format
Canvas URL should point to a directory in your server.
eg : http://www.mysite.com/fb/

Get the application id and secret key for your application.
Now we are going to build our application.

Download facebook php sdk from github. Upload files inside 'src' directory to  your server.

You need to enter your app id and secret key in the source code when communicating with Facebook server. They help identify your application uniquely among other applications. Facebook server uses these keys whenever it receives a request  from any application for validation purposes.
From the developer's perspective, it is a good practice to keep those configuration data separate from the general application.
Therefore, create a config.php file and add these data.

config.php

[sourcecode language="php"]
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'SECRET_KEY'
'cookie' => true,
'appBaseUrl' => 'http://apps.facebook.com/fb',
));
?>
[/sourcecode]



appBaseUrl represents the index.php file in your server where you hope to deploy your application.
In my case,  I specified my canvas URL as http://www.mysite.com/fb/
Accordingly, my Base URL should be something like http://apps.facebook.com/fb

We have included php sdk inside config.php. So no need to bother about it later. We only need to include config.php

Create index.php and add the following code.

[sourcecode language="php"]
<?php
require_once('config.php');

$user = $facebook->getUser();
$me = null;
if($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
}
}
if($me) {
echo 'User is logged in and has a valid session';
//header('Location:REDIRECTION_URL');
}
else {
$loginUrl = $facebook->getLoginUrl(array('req_perms' =>
'publish_stream',));

/**Use this code for iframe application*/
//echo '<script> top.location.href="'. $loginUrl .'"; </script>';
/**Use this code for third party application*/
header('Location: '.$loginUrl);
}

$logoutUrl = $facebook->getLogoutUrl(array('next' => 'http://apps.
facebook.com/fb/',));
?>

<br>

<a href ="#" onclick="top.location.href='<?php echo $logoutUrl; ?>';
return false;">Logout</a>


[/sourcecode]

upload both config.php and index.php to the same directory where facebook php sdk resides.
Test your application.
Happy Facebooking!

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...