search
HomeBackend DevelopmentPHP TutorialSocial Logins in PHP with HybridAuth

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>

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>

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>

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

For Facebook:

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

For Twitter:

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

For Google:

<code>$adapter = $hybridauth->authenticate( "Google" );</code>
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>

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

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>
This is the SQL for the database table.

<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
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>

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>

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>

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>

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>
Lastly, the getter method returns the user's name, email, and avatar URL.

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

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>

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>

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>

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

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

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

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

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

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

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>

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>

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>

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;

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 ...
}
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() );
        }

    }
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
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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.