Home > Backend Development > PHP Tutorial > Social Logins in PHP with HybridAuth

Social Logins in PHP with HybridAuth

Joseph Gordon-Levitt
Release: 2025-02-18 11:26:10
Original
537 people have browsed it

Many modern websites allow users to log in through their social network accounts. For example, the SitePoint community allows users to log in with their Facebook, Twitter, Google, Yahoo, or GitHub accounts without registering for a new account.

Social Logins in PHP with HybridAuth

This tutorial will introduce HybridAuth - a PHP library that simplifies the construction of social login capabilities.

HybridAuth acts as an abstract API between applications and various social APIs and identity providers.

Key Points

  • HybridAuth is a PHP library designed to simplify the integration of social login into your website and act as the middle layer between your application and various social APIs.
  • It is recommended to install HybridAuth through Composer, and specific credentials are required for each social network such as Facebook, Google, and Twitter to function properly.
  • This library uses OAuth for secure access, ensuring user credentials are protected during authentication.
  • HybridAuth allows custom user authentication processes, not relying on email or usernames, but using unique identifiers provided by social networks.
  • This tutorial provides a practical demonstration using the Slim PHP framework, detailing the steps from setting up an environment to writing a fully-featured demo application that handles user registration, login, and logout through a social network.

Installation

Composer is recommended to install HybridAuth. We will also use Slim as the basis for the sample application.

<code>{
    "require": {
        "slim/slim": "2.*",
        "hybridauth/hybridauth": "2.3.0"
    }
}</code>
Copy after login
Copy after login
Copy after login

Social login with HybridAuth

To use HybridAuth, copy the /vendor/hybridauth/hybridauth/hybridauth and config.php (HybridAuth endpoint files) in the index.php folder to your project root folder.

Rename the index.php file to hybrid.php because index.php will be used by the Slim framework for our demo application logic.

Fill the config.php file with your app (e.g. Facebook, Twitter app) credentials.

For example, if you want users to log into your website via Facebook, Google, and Twitter; your profile should look like this. My application URL is http://slim.local.

<code>return 
    [
        "base_url"   => "http://slim.local/",
        "providers"  => [
            "Google"   => [
                "enabled" => true,
                "keys"    => [ "id" => "", "secret" => "" ],
            ],
            "Facebook" => [
                "enabled"        => true,
                "keys"           => [ "id" => "", "secret" => "" ],
                "trustForwarded" => false
            ],
            "Twitter"  => [
                "enabled" => true,
                "keys"    => [ "key" => "", "secret" => "" ]
            ],
        ],
        "debug_mode" => true,
        "debug_file" => "bug.txt",
    ];</code>
Copy after login
Copy after login
Copy after login

Note: The base_url parameter must point to the HybridAuth endpoint file, in this case hybrid.php.

Refer to the HybridAuth configuration documentation for more information.

Next, load the vendor autoloader and instantiate the class.

<code>require 'vendor/autoload.php';
$hybridauth = new Hybrid_Auth( 'config.php' );</code>
Copy after login
Copy after login
Copy after login

Use the authenticate method to authenticate the user using the given provider.

For Facebook:

<code>$adapter = $hybridauth->authenticate( "Facebook" );</code>
Copy after login
Copy after login
Copy after login

For Twitter:

<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
Copy after login
Copy after login
Copy after login

For Google:

<code>$adapter = $hybridauth->authenticate( "Google" );</code>
Copy after login
Copy after login
Copy after login
The parameters passed to

must match the provider array key in the authenticate() file. config.phpAfter authentication, use the

method to retrieve the user's profile data. getUserProfile()

The
<code>{
    "require": {
        "slim/slim": "2.*",
        "hybridauth/hybridauth": "2.3.0"
    }
}</code>
Copy after login
Copy after login
Copy after login

variable will be an object that contains the returned user profile data. $user_profile

More social providers

To add more providers, such as GitHub, copy the

file from GitHub.php to a location in the application (in this case the provider directory). Load the file using a provider wrapper, where vendor/hybridauth/hybridauth/additional-providers/hybridauth-github/Providers is the path to the GitHub file and path is the name of its PHP class. class

<code>return 
    [
        "base_url"   => "http://slim.local/",
        "providers"  => [
            "Google"   => [
                "enabled" => true,
                "keys"    => [ "id" => "", "secret" => "" ],
            ],
            "Facebook" => [
                "enabled"        => true,
                "keys"           => [ "id" => "", "secret" => "" ],
                "trustForwarded" => false
            ],
            "Twitter"  => [
                "enabled" => true,
                "keys"    => [ "key" => "", "secret" => "" ]
            ],
        ],
        "debug_mode" => true,
        "debug_file" => "bug.txt",
    ];</code>
Copy after login
Copy after login
Copy after login
Use the

method of HybridAuth to authenticate users using GitHub, as shown below: authenticate()

<code>require 'vendor/autoload.php';
$hybridauth = new Hybrid_Auth( 'config.php' );</code>
Copy after login
Copy after login
Copy after login

Social login implementation

Usually, every website with a login and registration system uses the user's email address or username to identify and log in to their account. If you plan to implement social login, it is recommended not to use the user's username or email for authentication.

One of the reasons to object to this practice is that, for example, Twitter does not return the user's email address that has been authenticated through it. That is, the returned profile data does not contain the user's email.

Most, if not all, social providers, such as Facebook, Twitter, Google, LinkedIn and even GitHub, return a unique user ID number after authorization.

Do not log in to the user's account using the user's email, but use the identifier returned by the social provider, as shown below: Create a user account if the user does not have an account; log in if the user has an account Go to the website.

Writing a demo application

We will use the Slim PHP framework to build a simple web application to demonstrate practical examples of how to implement a social login using HybridAuth.

I assume you have HybridAuth and Slim frameworks installed. Otherwise, refer to the installation guide above.

Application Structure

<code>$adapter = $hybridauth->authenticate( "Facebook" );</code>
Copy after login
Copy after login
Copy after login
This is the SQL for the database table.

<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
Copy after login
Copy after login
Copy after login
Writing an application model

All code for the application model should be placed in the App_Model.php file in the src folder.

The file namespace is Model, followed by the class definition and constructor.

<code>$adapter = $hybridauth->authenticate( "Google" );</code>
Copy after login
Copy after login
Copy after login

Method Returns true if the identifier (user identification number) already exists in the database, otherwise returns false. identifier_exists

<code>$user_profile = $adapter->getUserProfile();</code>
Copy after login
Copy after login

Method Insert user profile data into the database. register_user

The
<code>"Github"   => [
    "enabled" => true,
    "keys"    => [
        "id"     => "",
        "secret" => ""
    ],
    "wrapper" => [ "path" => "providers/GitHub.php", "class" => "Hybrid_Providers_GitHub" ]
]</code>
Copy after login
Copy after login

method adds the created user session to the HybridAuth session when called (created after the provider successfully authorizes the user). login_user

<code>$adapter = $hybridauth->authenticate( "Github" );</code>
Copy after login
Copy after login

Method Delete or destroy a user's session when clicking the logout link. logout_user

<code>|-scr/
|----App_Model.php
|-templates/
|----login.php
|----welcome.php
|-vendor/
|-composer.json
|-config.php
|-hybrid.php
|-index.php
|-.htaccess</code>
Copy after login
Copy after login
Lastly, the getter method returns the user's name, email, and avatar URL.

<code>{
    "require": {
        "slim/slim": "2.*",
        "hybridauth/hybridauth": "2.3.0"
    }
}</code>
Copy after login
Copy after login
Copy after login

Register PSR-4 autoloader for the Model class by adding the following code to your composer.json file.

<code>return 
    [
        "base_url"   => "http://slim.local/",
        "providers"  => [
            "Google"   => [
                "enabled" => true,
                "keys"    => [ "id" => "", "secret" => "" ],
            ],
            "Facebook" => [
                "enabled"        => true,
                "keys"           => [ "id" => "", "secret" => "" ],
                "trustForwarded" => false
            ],
            "Twitter"  => [
                "enabled" => true,
                "keys"    => [ "key" => "", "secret" => "" ]
            ],
        ],
        "debug_mode" => true,
        "debug_file" => "bug.txt",
    ];</code>
Copy after login
Copy after login
Copy after login

Run composer dump-autoload to regenerate the vendor/autoload.php file.

Application Logic

Load composer in application index.php file automatically loads the file and instantiates Slim.

<code>require 'vendor/autoload.php';
$hybridauth = new Hybrid_Auth( 'config.php' );</code>
Copy after login
Copy after login
Copy after login

Create a directory called templates to store all template files, and then register or configure it in Slim as follows:

<code>$adapter = $hybridauth->authenticate( "Facebook" );</code>
Copy after login
Copy after login
Copy after login

Create a Slim database singleton resource that will return the database connection instance when called.

<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
Copy after login
Copy after login
Copy after login

Another singleton resource that returns a HybridAuth instance is also created.

<code>$adapter = $hybridauth->authenticate( "Google" );</code>
Copy after login
Copy after login
Copy after login

Instantiate the application model class by passing a database connection as a parameter.

<code>$user_profile = $adapter->getUserProfile();</code>
Copy after login
Copy after login

The following authenticate function when added as a parameter to the route, if the user is not logged in, it will redirect it to the login page.

<code>"Github"   => [
    "enabled" => true,
    "keys"    => [
        "id"     => "",
        "secret" => ""
    ],
    "wrapper" => [ "path" => "providers/GitHub.php", "class" => "Hybrid_Providers_GitHub" ]
]</code>
Copy after login
Copy after login

Redirects the logged out user to the login page when he accesses the app's home page or index page.

<code>$adapter = $hybridauth->authenticate( "Github" );</code>
Copy after login
Copy after login

The following is the routing definition for social login links. That is, when the link http://slim.local/login/facebook is clicked, HybridAuth redirects the user to Facebook for authorization. The same goes for Twitter http://slim.local/login/twitter, Google http://slim.local/login/google and all other supported providers.

<code>|-scr/
|----App_Model.php
|-templates/
|----login.php
|----welcome.php
|-vendor/
|-composer.json
|-config.php
|-hybrid.php
|-index.php
|-.htaccess</code>
Copy after login
Copy after login

Calling the authenticate() method of HybridAuth redirects the user to the given social provider.

After successful authorization, the $user_profile variable will populate the user profile data.

Call the identifier_exists() method to check whether the user identifier exists in the database. If true, the user logs into the website. Otherwise, an account is created for the user and the user is logged in.

This is the code to log out the route.

CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
PRIMARY KEY  (id),
  `identifier` varchar(50) NOT NULL,
UNIQUE KEY `identifier` (`identifier`),
  `email` varchar(50) DEFAULT NULL,
  `first_name` varchar(20) DEFAULT NULL,
  `last_name` varchar(20) DEFAULT NULL,
  `avatar_url` varchar(255)
) ENGINE=InnoDB;
Copy after login

The logout_user method we have discussed in the model class is called to destroy the user session, and also to log out of the user's connection provider. Hybrid_Auth::logoutAllProviders()

Route of the welcome page redirected to by the user after logging in:

<?php namespace Model;

class App_Model
{

    /** @var object Database connection */
    private $conn;

    /**
     * Instantiate the model class.
     *
     * @param object $db_connection DB connection
     */
    public function __construct(\PDO $db_connection)
    {
        $this->conn = $db_connection;
    }

    // ... rest of the methods ...
}
Copy after login
Finally, run the Slim application.

/**
     * Check if a HybridAuth identifier already exists in DB
     *
     * @param int $identifier
     *
     * @return bool
     */
    public function identifier_exists($identifier)
    {
        try {
            $sql    = 'SELECT identifier FROM users';
            $query  = $this->conn->query($sql);
            $result = $query->fetchAll(\PDO::FETCH_COLUMN, 0);

            return in_array($identifier, $result);
        } catch ( \PDOException $e ) {
            die( $e->getMessage() );
        }

    }
Copy after login
See the application's GitHub repository for the complete source code.

Conclusion

In this article, we learned how to integrate social login capabilities with websites using the powerful and robust HybridAuth PHP library.

If you have any questions or contributions, please let us know in the comments.

FAQ (FAQ) for social login with PHP and HybridAuth

What is HybridAuth and how is it used with PHP for social login?

HybridAuth is a popular open source social login PHP library. It allows web developers to easily build social applications by providing an easy way to authenticate users through their social media accounts. HybridAuth acts as an abstract API between applications and various social APIs and identity providers such as Facebook, Twitter, and Google. It works by integrating with existing login systems in PHP applications and adding social login capabilities.

How to install and configure HybridAuth in my PHP application?

HybridAuth can be installed through Composer (the dependency management tool in PHP). After installation, you need to configure it by setting up the provider you want to use (social network). Each provider requires a unique set of parameters, such as keys and keys, which you can obtain by creating applications on the developer platforms of each social network.

What is the security level of HybridAuth for social login?

HybridAuth is very secure because it uses OAuth, an open access delegate standard. OAuth provides secure designated access, meaning that users can grant websites permission to access their information on other websites without providing them with a password. This makes HybridAuth a secure option for social login.

Can I use HybridAuth for social login on multiple websites?

Yes, HybridAuth can be used on multiple websites. You just need to use the correct callback URL configuration library for each website. This makes it a flexible solution for developers who manage multiple websites.

How to deal with errors in HybridAuth?

HybridAuth has a built-in error handling system. When an error occurs, it throws an exception that you can catch and handle based on your application's error handling policy. This makes debugging and fixing issues easier.

Can I customize the look and style of HybridAuth’s social login button?

Yes, you can customize the look and style of the social login button. HybridAuth offers social login capabilities, but the design and layout of the buttons are entirely up to you.

How to update the HybridAuth library in my PHP application?

Updating HybridAuth is as easy as running a command in Composer. This ensures that you always have the latest version with all security patches and updates.

Can I use HybridAuth with other PHP frameworks?

Yes, HybridAuth is not a framework and can be used with any PHP framework. This makes it a versatile choice for developers using different PHP frameworks.

How to test HybridAuth's social login in my local development environment?

Testing social login locally can be tricky because social networks require valid callback URLs. However, you can expose your local server to the internet using tools such as ngrok and use that URL as a callback URL.

Can I authenticate users with non-social accounts such as emails and passwords using HybridAuth?

No, HybridAuth is designed for social login. For traditional email and password authentication, you need to use other PHP libraries or build your own authentication system.

The output maintains the original image formatting and placement. The text has been paraphrased and reorganized to improve flow and readability while preserving the original meaning. The code examples remain unchanged.

The above is the detailed content of Social Logins in PHP with HybridAuth. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template