Implementation of Facebook login in FuelPHP

Sep 10, 2020 PHP Facebook FuelPHP facebook login


It’s a little late, but it’s a memo when I implemented Facebook login with FuelPHP. FuelPHP makes it easy to implement social login by using a package called Opauth.

#Create Facebook app

This isn’t limited to FuelPHP, but in order to implement social login with Facebook, you must first create a Facebook app for social login on Facebook. To create a Facebook app, you need to register as a Facebook developer, so first register as a developer.

Developer registration

While logged in to Facebook with the account you want to register as a developer, access the following page.

Click “Start Guide” at the top right of the page to open the registration window. After that, if you follow the instructions on the screen, the developer registration will be completed. By the way, phone number verification or credit card verification is required for developer registration, so prepare either one.

App creation

After registering as a developer, the start guide part of will change to “My apps”. Click “My App” to go to the Facebook app creation screen.

Here, select the app you want to create and create it, and the app ID and secret will be created. These two will be needed to create a Facebook app, so record them somewhere. (App settings will be set as appropriate, but omitted here)

#FuelPHP side settings

Once you’ve created your Facebook app, FuelPHP is all you need to do. The following is an example of FuelPHP-1.8.2.

FuelPHP installation

First, install FuelPHP. Any method is fine, but for example, it looks like the following. For more information, see the pages that explain the installation of various FuelPHP.

% git clone --recursive git: //
% cd fuel
% php composer.phar update
% php oil refine install

From now on, it is assumed that FuelPHP is installed under / project / test1.

Package installation

Next, install the packages needed to implement Facebook login. The package can be installed using Composer, so first add it to composer.json as shown below.

"opauth / opauth": "0.4. *",
"opauth / facebook": "dev-master",

Install the package while self-updated Composer once as shown below.

% php composer.phar self-update
% php composer.phar update


First, enable the auth package by setting config.php as follows.

'always_load' => array (
'packages' => array (

Next, copy packages / auth / config / opauth.php underapp / config /and include the Facebook app ID and secret you recorded as shown below. Also, if you want to get email information as well, you can’t get email information by default, so set scope and fields as shown below.

'Strategy' => array (
'Facebook' => array (
'app_id' => '1111111111111111',
'app_secret' =>'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
         'scope' =>'email',
         'fields' =>'email, first_name, last_name, name',

DB creation

As with normal FuelPHP, prepare a DB environment such as MySQL and configure the settings on the FuelPHP side. Once you have a DB connection from FuelPHP, execute the following to create the DB table required for Opauth.

% php / project / test1 / oil refine migrate --packages = auth

This completes the setting relationship.


Implement Facebook login using the settings you have made so far. Here, as a very simple example, create the following site.

| URL path | Overview | |: ———– |: ———— | | / sample / index | Can be displayed only when logged in (redirect to / user / login if not logged in) | / user / login | Facebook Show link to log in | / user / auth / facebook | Facebook login

/ sample / index

First, implement / sample / index that can be displayed only when you are logged in. Quickly generate below.

% php / project / test1 / oil g controller sample index
Creating view: /project/test1/fuel/app/views/template.php
Creating view: /project/test1/fuel/app/views/sample/index.php
Creating controller: /project/test1/fuel/app/classes/controller/sample.php

app / views / sample / index.php is the content that is displayed when you are logged in, so modify it to the content you want to display appropriately. app / classes / contourer / sample.php addsbefore ()to its generated state to redirect you to the login page when you are not logged in.

<? php

class Controller_Sample extends Controller_Template
public function before ()
        parent :: before ();
        if (! Auth :: check ())
            Session :: set_flash ('error','no login');
            Response :: redirect ('user / login');

public function action_index ()
$ data ["subnav"] = array ('index' =>'active');
$ this-> template-> title ='Sample ┬╗Index';
$ this-> template-> content = View :: forge ('sample / index', $ data);


/ user / login

Next, implement / user / login to display the link to log in. If you are not logged in, you will be redirected to this page. This is also a quick way to generate as follows.

% php / project / test1 / oil g controller user login
Creating view: /project/test1/fuel/app/views/user/login.php
Creating controller: /project/test1/fuel/app/classes/controller/user.php

app / views / user / login.php should transition to / user / auth / facebook when logging in to Facebook. Below is an example of just putting a link.

<ul class = "nav nav-pills">
<li class ='<? php echo Arr :: get ($ subnav, "login");?>'> <? Php echo Html :: anchor ('user / auth / facebook','Login with Facebook') ;?> </ li>
</ ul>

For app / classes / controller / user.php, you don’t have to do anything about / user / login for the time being.

/ user / auth / facebook

We will implement Facebook login, which is the main subject of this time. Basically, there is no problem if you implement it according to the official document below.

This time, the path is /user/auth/facebook, so we will implement the Facebook login code in app / classes / controller / user.php.

action_auth ()

First of all, you need to implement the action_auth () method that is directly related to the path in / usr / auth / facebook, but this method is OK with the following contents as documented.

public function action_oauth ($ provider = null)
// Go out if you don't have an OAuth provider to call
if ($ provider === null)
\ Messages :: error (__ ('login-no-provider-specified'));
\ Response :: redirect_back ();

// Read Opauth, will redirect the provider's strategy to the read provider
\ Auth_Opauth :: forge ();
`````As stated in the comment, if a valid provider (facebook in this case) is specified, `\ Auth_Opauth :: forge ()` will redirect you to the page for the specified provider.

#### action_callback ()

`action_callback ()` is the method that will be called back after logging in on the Facebook page.
Now get the Facebook authentication result.

```app / classes / controller / user.php
public function action_callback ()
    try {
        $ opauth = Auth_Opauth :: forge (false);
        $ status = $ opauth-> login_or_register ();
        $ url ='sample / index';
        Log :: warning ("login_or_register:". $ Status);
        switch ($ status) {
                // You are logged in and your provider is associated with this user
                // Associated with a known provider and logged in with that account
                // Login with this provider is not associated, so you need to create a local account
                $ url = "user / register";
                // Login with this provider is not associated but enough information was returned so I automatically registered a local account
            default: default:
                // Unable to determine status
Response :: redirect ($ url);
    } catch (OpauthException $ e) {
        // Authentication failed
    } catch (OpauthCancelException $ e) {
        // Authentication failed (cancelled)

Since the authentication result can be obtained by login_or_register (), it is judged using this. Here, ** linked ** / ** logged_in ** / ** registered ** indicates that login is complete, so we redirect to / sample / index.

At the time of ** register **, the Facebook login is successful, but it is not yet associated with the local account (the local account has not been created), so redirect to / user / register to associate with the local account. I am doing it.

action_register ()

action_register () processes to create a local account while associating Facebook login information.

public function action_register ()
    if ($ authentication = Session :: get ('auth-strategy.authentication', array ()))
            $ user = Session :: get ('auth-strategy.user');
            $ user_id = Auth :: create_user (
                $ user ['email'],
                $ user ['email'],
                Config :: get ('application.user.default_group', 1),
                array (
                    'fullname' => $ user ['name'],

            if ($ user_id)
                $ opauth = Auth_Opauth :: forge (false);

                // call Opauth to link the provider login with the local user
                $ insert_id = $ opauth-> link_provider (array (array (
                    'parent_id' => $ user_id,
                    'provider' => $ authentication ['provider'],
                    'uid' => $ authentication ['uid'],
                    'access_token' => $ authentication ['access_token'],
                    'secret' => $ authentication ['secret'],
                    'refresh_token' => $ authentication ['refresh_token'],
                    'expires' => $ authentication ['expires'],
                    'created_at' => time (),
                Auth :: instance ()-> force_login ((int) $ user_id);

                Session :: set_flash ('success', __ (''));
                Response :: redirect_back ('calendar');
            else else
                \ Session :: set_flash ('error', __ ('login.account-creation-failed'));

        // catch exceptions from the create_user () call
        catch (SimpleUserUpdateException $ e)
            // Duplicate email address
            if ($ e-> getCode () == 2)
                Session :: set_flash ('error', __ (''));

            // Duplicate username
            elseif ($ e-> getCode () == 3)
                Session :: set_flash ('error', __ ('login.username-already-exists'));

            // This can't happen, but it's not always the case ...
            else else
                Session :: set_flash ('error', $ e-> getMessage ());
    else else
        Session :: set_flash ('error','Failed to retrieve a user information from the provider.');

    Response :: redirect_back ('user / login');

You can get the authentication information with Session :: get ('auth-strategy.authentication') and the user information associated with it with Session :: get ('auth-strategy.user'). I use these to create a local user and associate it with the provider login.

in conclusion

With the implementation so far, you can confirm that Facebook login works. Once you understand the flow, you can implement it quite easily, so it seems that you can use it in various ways. I knew Opauth existed, but it was a hassle and I left it for a long time, but I wish I had used it earlier. In addition to Facebook, Opauth seems to support at least Twitter and Google.