Current Location: Home> Latest Articles> PHP Security Authentication Tutorial: Implement Multi-Factor Authentication with Authy

PHP Security Authentication Tutorial: Implement Multi-Factor Authentication with Authy

gitbox 2025-06-27

Introduction

Authy is a tool focused on multi-factor authentication (MFA), offering additional security for applications. With MFA, users need to provide not only a password but also a verification code sent via SMS or generated by a mobile app, effectively reducing the risk of account compromise.

Installing Authy

Register an Authy Account

First, register an account on the official Authy website. After registration, you will receive an application ID and API key, which will be used in the next steps.

Install the Authy PHP SDK

Authy provides an official SDK for PHP to help developers integrate quickly. Run the following command in the terminal at your project root to install the SDK:

composer require authy/php

After installation, you can call Authy interfaces in your code.

Integrate the Authy SDK

Configure Authy

Log in to the Authy dashboard and get your application ID and API key from the “Settings” page, then configure them in your PHP code.

Create an Authy Instance

use Authy\AuthyApi;
$authyApiKey = "your_authy_api_key";
$authy = new AuthyApi($authyApiKey);

Replace “your_authy_api_key” with your actual Authy API key.

Send Verification Code

During user login or registration, you can send a verification code to the user's phone with the following code:

$phoneNumber = "user_phone_number";
$user = $authy->registerUser($email, $phoneNumber, $countryCode);
$authyId = $user->id();
$verification = $authy->phoneVerificationStart($authyId, $countryCode, $phoneNumber);
$verificationStatus = $verification->ok() ? "success" : "failure";

Replace “user_phone_number” with the user's actual phone number and provide the corresponding country code.

Verify the Code

Once the user inputs the received verification code, you can verify it with the following code:

$verificationCode = "user_verification_code";
$verification = $authy->phoneVerificationCheck($authyId, $countryCode, $phoneNumber, $verificationCode);
$verificationStatus = $verification->ok() ? "success" : "failure";

Replace “user_verification_code” with the code entered by the user.

Enable Authy Two-Factor Authentication

After successful verification, you can enable Authy's two-factor authentication feature to further secure user accounts:

$authy->enableTwoFactorAuth($authyId, "on");

This activates two-factor authentication and links the user with their Authy account.

Conclusion

Integrating Authy to implement multi-factor authentication in PHP projects significantly enhances application security and provides stronger protection for user accounts. Following the steps in this article, developers can quickly get started with Authy and complete the full integration process from SDK installation to feature activation.