TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

How to build Facebook login using CakePHP Facebook Login Plugin

Facebook connect enables users to login to your application instantly with a Facebook Account. It saves user from checking email to verify his account, which will greatly enhance your application's user experience.

We have published a follow-up tutorial at How to integrate Facebook login with CakePHP 3.

In this tutorial, we will show you how to implement Facebook login for you CakePHP application using a great plugin "CakePHP Facebook".

Prepration

  1. Download CakePHP Facebook Plugin from Github.
  2. Unpack downloaded folder, and copy it to directory "app/plugins/facebook"
  3. We are using CakePHP 1.3.2 in this tutorial.
  4. CakePHP Facebook Plugin is integrated with CakePHP Auth component, so we will assume you are using Auth component for your application.
  5. For simplicity, in this tutorial, we will only have one user controller, and after user logins, it will show a demo home page, and inside the home page, there is a logout button.

Setup Facebook Plugin

Copy and rename file "app/plugins/facebook/config/facebook.php.example" to "app/config/facebook.php". And then you will need to create a Facebook App, and supply its appId,apiKey, secret here. Please note this is required for Facebook login to work.

Setup Database

You may already have a database set up if you are trying to implement Facebook login in your existing project. In this demo, we will have a simple users table as below. Take note if you are doing this in a existing database, you will need to add one more field "facebook_id" to the users table. If you are strictly following this tutorial, please import sql below to your database to create a users table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(250) NOT NULL,
  `password` varchar(250) NOT NULL,
  `facebook_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Setup Controller

Create users_controller.php under /app/controllers folder.

<?php
class UsersController extends AppController {
    var $name = 'Users';
    var $components = array('Facebook.Connect','Auth'); //1
    var $helpers    = array('Facebook.Facebook');       //2
     
    function beforeFilter() {
         $this->Auth->loginRedirect = array('action' => 'index');     //3    
         $this->layout='facebook';                                    //4    
    }
     
    function index() {                                  //5
         
    }
 
    function login() {                                  //6
         
    }
     
    function logout() {                                 //7
        $this->Session->destroy();
        $this->redirect($this->Auth->logout());
    }
}
?>
  1. Include "Connect" component from Facebook Plugin and "Auth" from core files.
  2. Include "Facebook" helper from Facebook Plugin.
  3. We want user to be redirected to index page after successfully login.
  4. We will have to use a special layout file for our views, which will be created next step.
  5. This will be the home page after users has login.
  6. Dummy login function for Auth component.
  7. Inside logout function, we explicitly call Session->destroy() to delete the whole session variable, this is due to a bug, which Facebook will always try to fetch its content via a session variable, so we will have to explicitly delete the whole session.

Setup Layout

Create a layout file "app/views/layouts/facebook.ctp" and copy the content below to the file.

<?php echo $this->Facebook->html(); ?>
<head>
    <?php echo $html->css('cake.generic'); ?>
</head>
<body>
    <!-- content -->
    <div id="content" >
        <?php echo $content_for_layout; ?>
    </div>
    <!-- end content -->
</body>
<?php echo $this->Facebook->init(); ?> 
</html>

Nothing special about this file, except we are calling Facebook helper at the beginning and end of it. This basically will include needed Javascript from Facebook and invoke some specific Javacript calls to make the Facebook login and logout button work.

Setup View

View pages are the most important part of setting up Facebook login, please pay attention in this section.

Create two view files "app/views/users/login.ctp" and "app/views/users/index.ctp"

  • login.ctp
<?php      
echo $this->Facebook->login(array('width' => '174','height'=>'25','scope' => 'email'),
                     __('Login with Facebook',true));
?

Here is the magic happens, Facebook->login() will create a Facebook login button for us, and when user clicks on it, it will prompt user to login using Facebook account, and when that is done. Facebook Connect component will automatically create a user account for this user and let him login using Auth component.

  • index.ctp
  <h2>Home Page</h2>
  <?php
  echo $this->Facebook->logout(array('redirect' => array('controller' => 'users', 'action' => 'logout')));
  ?>

This page is simple, but it is also the most important. Here we use Facebook helper to render a logout button. Pay attention to the "redirect" parameter of the method. Keep in mind, Facebook logout button will only log user out of Facebook, it is your responsibility to log them out of your application, thus you have to redirect user to logout method.

The End

Now you should have a simple authentication application powered by Facebook. You should be able to login and logout of the application using you Facebook account.

Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.