Login with Facebook using PHP SDK in CakePHP

 

Here we used PHP SDK 3.0 and CakePHP 2.X for the process of authentication and authorizing users for your app.

For Creating an App, which you can obtain from the App Dashboard.
You need App Id and App Secret for integration of the facebook login in cakephp.

Login with Facebook Using CakePHP

Live DemoLive Demo

Download Script

In this CakePHP module we included the Facebook PHP SDK 3.0 in vendors of the app directory.And we define Some variables in Core.php

define('BASE_URL','http://'.$_SERVER['HTTP_HOST'].'/fb_cakephp/');

And We create one file which is facebook.php in config folder for the define of AppId and Appsecret.

$config = array(
  'Facebook' => array(
  	'appId' => 'YOUR APP ID',
        'secret' => 'YOUR APP SECRET',
   )
);

We create one Controller which is FacebookCpsController.php

<?php
App::uses('Controller', 'Controller');
App::import('Vendor', 'Facebook',array('file'=>'Facebook'.DS.'facebook.php'));
class FacebookCpsController extends AppController {

	public $name = 'FacebookCps';
	public $uses=array();

	public function index(){
		$this->layout=false;
	}

	function login()
	{
		Configure::load('facebook');
		$appId=Configure::read('Facebook.appId');
		$app_secret=Configure::read('Facebook.secret');
		$facebook = new Facebook(array(
				'appId'		=>  $appId,
				'secret'	=> $app_secret,
				));
		$loginUrl = $facebook->getLoginUrl(array(
			'scope'			=> 'email,read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos',
			'redirect_uri'	=> BASE_URL.'facebook_cps/facebook_connect',
			'display'=>'popup'
			));
		$this->redirect($loginUrl);
   	}

	function facebook_connect()
	{
	    Configure::load('facebook');
	    $appId=Configure::read('Facebook.appId');
	    $app_secret=Configure::read('Facebook.secret');

	   	 $facebook = new Facebook(array(
		'appId'		=>  $appId,
		'secret'	=> $app_secret,
		));

	    $user = $facebook->getUser();
		if($user){
			try{
				$user_profile = $facebook->api('/me');
				$params=array('next' => BASE_URL.'facebook_cps/facebook_logout');
				$logout =$facebook->getLogoutUrl($params);
				$this->Session->write('User',$user_profile);
				$this->Session->write('logout',$logout);
			}
			catch(FacebookApiException $e){
				error_log($e);
				$user = NULL;
			}
		}
	   else
	   {
		    $this->Session->setFlash('Sorry.Please try again','default',array('class'=>'msg_req'));
		    $this->redirect(array('action'=>'index'));
	   }
   }

   function facebook_logout(){
		$this->Session->delete('User');
		$this->Session->delete('logout');
		$this->redirect(array('action'=>'index'));
   }
}
?>

Here We create two view files for the FacebookCpsController which are located in app/View/FacebookCps directory.

index.ctp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login with Facebook In CakePHP</title>
<?php
echo $this->Html->script('http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js');
echo $this->Html->script('oauthpopup');  ?>
<script type="text/javascript">
$(document).ready(function(){
    $('#facebook').click(function(e){
        $.oauthpopup({
            path: 'facebook_cps/login',
			width:600,
			height:300,
            callback: function(){
                window.location.reload();
            }
        });
		e.preventDefault();
    });
});
</script>
</head>
<body>
<?php
$ses_user=$this->Session->read('User');
$logout=$this->Session->read('logout');
if(!$this->Session->check('User') && empty($ses_user))   {
echo $this->Html->image('facebook.png',array('id'=>'facebook','style'=>'cursor:pointer;float:left;margin-left:550px;'));
 }  else{

 echo '<img src="https://graph.facebook.com/'. $ses_user['id'] .'/picture" width="30" height="30"/><div>'.$ses_user['name'].'</div>';
	echo '<a href="'.$logout.'">Logout</a>';

}
	?>
</body>
</html>

facebook_connect.ctp

<script type="text/javascript">
window.close();
</script>

Here I used one jquery plugin oauthpopup.jswhich is used for popup
(this file is located in app/webroot/js directory)

oauthpopup.js

(function (jQuery) {
    jQuery.oauthpopup = function (options) {
        options.windowName = options.windowName || 'ConnectWithOAuth';
        options.windowOptions = options.windowOptions || 'location=0,status=0,width='+options.width+',height='+options.height+',scrollbars=1';
        options.callback = options.callback || function () {
            window.location.reload();
        };
        var that = this;
        that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
        that._oauthInterval = window.setInterval(function () {
            if (that._oauthWindow.closed) {
                window.clearInterval(that._oauthInterval);
                options.callback();
            }
        }, 1000);
    };
})(jQuery);

In the PHP SDK 3.0,we change the facebook.php file.For the Session We uses the CakePHP core data source which is CakeSession. facebook.php file is located at app/Vendor/Facebook directory

facebook.php

//included this line the above class
App::uses('CakeSession', 'Model/Datasource');

  public function __construct($config) {
    if (!session_id()) {
//insted of session_start() we used CakeSession::start()
      CakeSession::start();
    }
    parent::__construct($config);
    if (!empty($config['sharedSession'])) {
      $this->initSharedSession();
    }
  }

43 Comments

  1. nice post………

  2. very helpfull!! thx!

  3. nafees ahmed

    nice work thanks

  4. Sivabalan

    Hai i am new to cakephp. I tried to facebook login through cakephp using your code. currently i am trying in
    my localhost. In this i got facebook login but it is not redirecting to my page. Please help me to do this

  5. Sahil kapoor

    Nyc man..!!

  6. Thank’s.
    It works nice and was very helpfull to me.

  7. Thank,s

  8. Abhishek

    Nice Post

  9. Very helpfull!!!!

Leave a Reply