How to Build Passwordless Auth Using TOTP With Twilio Verify in PHP

August 10, 2026
Written by

AI generated summary
  • Deploy passwordless authentication using TOTP with Twilio Verify.
  • This enhances security and user experience by eliminating passwords.
  • Building the app involves QR code scanning, creating factors, and validating TOTP codes.

This summary was generated by AI and reviewed by the Twilio team.

How to Build Passwordless Auth Using TOTP With Twilio Verify in PHP

Typing or generating a unique password for every new account or website is a hassle. Although password managers help, passwordless auth (authentication) offers a more streamlined and secure alternative.

In this tutorial, you will learn about passwordless auth, and build a PHP app that uses Twilio Verify to implement it.

Programming language support

You can find this tutorial in the following programming languages:

Prerequisites

Before you begin, ensure you have the following:

  • A free Twilio account. Click here to create a free account if you are new to Twilio.
  • An authentication app, such as Twilio Authy
  • PHP (ideally, version 8.5)
  • Your favourite text editor or IDE (such as neovim or Visual Studio Code)
  • Your favourite web browser

Architecture

This application will be a simplistic web-based application, split up over three stages.

  • Stage one: the user will submit their username to begin setting up Two-factor Authentication (2FA).
  • Stage two: they'll set up a TOTP entry in their authenticator app. They'll do this with their authenticator app by scanning a QR code or entering a unique code. Then, they'll submit the initial code that their authenticator app generates for them. If the code is valid, their account is ready to use.
  • Stage three:, They can validate future codes which their authenticator app generates for them in the final form in the application.

What is passwordless auth?

Passwordless auth is an authentication method where the user does not need a password in order to log into an app or system. Rather, the user's mobile device receives a one-time code. In this authentication method, users are authenticated using other unique and more secure alternatives like Time-based One-time Passwords (TOTP, or Soft Token), SMS, PasskeysSilent Network Authentication (SNA), Voice, or email notification.

Here's a breakdown of how it works, using TOTP:

  1. User initiation: When a user creates an account, instead of entering a password, they create a new Factor resource with Twilio Verify — initially marked as unverified — seeding it with a unique (auto-generated) identifier.
  2. Scan the QR code with an authenticator app: Using an authenticator app such as Twilio Authy, they scan the QR code then enter the code that the authenticator app provides. The code is validated using Twilio Verify. If the code is valid the Factor is marked verified. The authenticator app can now provide time-based codes to use in the future, when logging in, which Twilio Verify will verify.
  3. Code validation: When the user logs in, they enter their username and a TOTP code generated by their authenticator app. The application then uses Twilio Verify to validate the code along with their unique identifier.

This approach significantly enhances security by leveraging the inherent security features of the user's mobile device as a second factor in the authentication process. It also eliminates the need for them to memorize passwords, thereby simplifying the authentication process and enhancing user convenience.

Passwordless authentication has additional advantages, including the following:

  • Enhanced security: Reduces the risk of password-related breaches.
  • Convenience: Eliminates the need for users to remember and manage multiple passwords.
  • Reduced friction: Streamlines the login process, improving the user experience.
  • Scalability: Easily scalable with Twilio's infrastructure.

Build the app

Step 1: Set up the project

Set up a new project using the Twilio / Slim Base Project, by running the following command, where you store your PHP projects:

composer create-project settermjd/twilio-slim-base-project twilio-verify-totp-php
cd twilio-verify-totp-php
mkdir -p templates public/css

Step 2: Install the required dependencies

Next, install the required dependencies, by running the following:

composer require bryanjhv/slim-session chillerlan/php-qrcode slim/flash slim/twig-view twilio/sdk vlucas/phpdotenv

In case you're not familiar with them, here's a short description of the dependencies that you just installed:

  • chillerlan PHP-QRCode: This simplifies generating QR codes in the application
  • PHP dotenv: Loads environment variables from .env into getenv(), $_ENV and $_SERVER automagically.
  • Slim Flash: This adds flash message support, which simplifies providing UI feedback throughout the application
  • Slim Session: Simple middleware for Slim Framework 4, that allows managing PHP built-in sessions
  • Slim Framework Twig View: This is a Slim Framework view helper built on top of the Twig templating component.
  • Twilio's PHP Helper Library: This simplifies integrating with Twilio in PHP

Now, open the project directory in your preferred text editor or IDE.

Step 3: Set the required environment variables

Dotenv files (commonly named .env) are used to store the configuration information that your app needs during development, separate from the application's code. For this tutorial, it will be your Twilio credentials (i.e., your Twilio Account SID and Auth Token) and a Verify Service SID.

In your project's top-level directory, open .env and add the following variable to the end of the file; the other two variables have already been set in the file.

TWILIO_VERIFY_SERVICE_SID=

You next need to retrieve the credentials to set as their values. To do that, sign into the Twilio Console. There, click the black and white up arrow at the bottom of the page, and you should see your Account SID and Auth Token in the Workbench; as shown in the image below.

Dark-themed Twilio workbench dashboard showing API credentials, quick actions, and different tabs.

Copy these values and paste them into .env as the values for TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN.

Next, navigate to Products and Services > Verify > Services. On this page, click Create new. Then, fill out the initial form with the configuration values shown in the screenshot below, and click Continue.

Twilio interface displaying options to create a new verification service with SMS, WhatsApp, Email, and Voice channels.

In the next step, leave Enable Fraud Guard set to "Yes" and click Continue to finish creating the service.

Twilio popup window configuring SMS Fraud Guard with yes or no option

After creating the service, copy the Service SID and paste it into .env as the value of TWILIO_VERIFY_SERVICE_SID.

Screenshot of Twilio service settings page showing options for Friendly Name, Service SID, and Branded Sender ID.

Step 4: Build the base PHP application

The next thing to do is to load the environment variables. To do that, replace the code in public/index.php with the code below:

<?php

declare(strict_types=1);

use App\Application;
use DI\Container;
use Dotenv\Dotenv;
use SlimSession\Helper;
use Slim\Factory\AppFactory;
use Slim\Flash\Messages;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twilio\Rest\Client;

require __DIR__ . '/../vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
$dotenv->required(
    [
        'TWILIO_ACCOUNT_SID',
        'TWILIO_AUTH_TOKEN',
        'TWILIO_VERIFY_SERVICE_SID'
    ]
)->notEmpty();

$container = new Container();
$container->set(
    Client::class,
    fn(): Client => new Client(
        $_ENV['TWILIO_ACCOUNT_SID'],
        $_ENV['TWILIO_AUTH_TOKEN'],
    ),
);

$container->set('session', function () {
    return new Helper();
});

$container->set(Messages::class, function () {
    return new Messages();
});

AppFactory::setContainer($container);
$app = AppFactory::createFromContainer($container);
$app->add(
    new \Slim\Middleware\Session([
        'autorefresh' => true,
        'lifetime'    => '1 hour',
        'name'        => 'app_session',
    ]),
);

$twig = Twig::create(__DIR__ . '/../templates', ['cache' => false]);

$app->add(TwigMiddleware::create($app, $twig));

$application = new Application($app);
$application->setupRoutes();
$application->run();

The updated code, above, loads environment variables from the variables defined in .env, using PHP dotenv, ensuring that TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_VERIFY_SERVICE_SID have been set and are not empty. Then, it adds session and Twig template support to the application, along with a Twilio Rest Client object to the application's DI container; which will be used when sending and verifying OTP codes.

With that done, update src/Application.php's constructor to match the following:

public function __construct(private readonly SlimApp $app)
{
    $app->add(new ContentLengthMiddleware());
    $app->addBodyParsingMiddleware();
    $app->addRoutingMiddleware();
    $app->addErrorMiddleware(true, true, true);
 
    $this->session          = new SlimSessionHelper();
    $this->verifyServiceSid = $_ENV['TWILIO_VERIFY_SERVICE_SID'];
    $twilio = $this->app->getContainer()->get(Client::class);
    assert($twilio instanceof Client);
    $this->twilio = $twilio;
}

Then, add the following private class variables to the class:

private Client $twilio;
private SlimSessionHelper $session;
private string $verifyServiceSid;

And after that, add the following use statement to the top of the file:

use SlimSession\Helper as SlimSessionHelper;
use Twilio\Rest\Client;

use function assert;

The revised constructor adds the session support that was initialised in public/index.php to the class, and stores the TWILIO_VERIFY_SERVICE_SID as a class member variable.

Step 5: Add the ability to create a new TOTP Factor

Now, you'll add the first feature of the application: the ability to create a new TOTP Factor. To do that, add the following function to src/Application.php in place of the existing handleDefaultRoute() function.

public function displayCreateTotpFactorForm(
    ServerRequestInterface $request,
    ResponseInterface $response,
): ResponseInterface {
    $view = Twig::fromRequest($request);
    return $view->render($response, 'enter-username.html.twig', []);
}

The displayCreateTotpFactorForm() function uses Twig to render templates/enter-username.html.twig. This function will be called in response to GET requests to the application's default route "/", rendering a form for the user to enter their username as the first stage in the TOTP setup process.

Now, in the templates directory, create a new file named enter-username.html.twig, and in that file, paste the code below:

<!DOCTYPE html>
<html>
<head>
    <title>Register New TOTP Factor</title>
    <link href="https://assets.twilio.com/public_assets/paste-fonts/1.5.2/fonts.css" rel="stylesheet">
    <link href="/css/styles.css" rel="stylesheet">
</head>
<body class="container">
    <main>
        <h1>Register New TOTP Factor</h1>
        <p class="mt-60">
        This demo of the <a href="https://www.twilio.com/docs/verify/api">Twilio Verify API</a> shows how to set up two-factor authentication (2FA) with a third-party authenticator app like <a href="https://authy.com/download/">Authy</a> or Google Authenticator using the <a href="https://www.twilio.com/docs/glossary/totp">time-based one-time password (TOTP)</a> standard.
        </p>
        <hr class="mt-60">
        <form action="/" method="post" class="mt-60 mb-60">
            <label for="username">Enter your username:</label>
            <div class="mt-20" style="display: flex; flex: auto; column-gap: 0.25rem; flex-shrink: 0;">
                <input
                    id="username"
                    inputmode="text"
                    name="username"
                    required
                    style="flex-shrink: 1;"
                    type="text"
                >
                <button
                    class="primary"
                    style="flex-grow: 1; white-space: nowrap"
                    type="submit"
                >Set up two-factor authentication</button>
            </div>
        </form>
        <div style="background-color: #d6ebf0; padding: 2em; border-radius: 0.25rem;" class="mb-60 mt-60">
            <h2 class="mb-60">Create a New Factor | What's happening here:</h2>
            <p style="line-height: 1.5;" class="mb-60">
                The API is <strong>creating a new TOTP <a href="https://www.twilio.com/docs/verify/api/factor#create-a-new-factor-resource">Factor</a></strong> when you click "Set up two-factor authentication".
                This is how the Verify API connects a user (<code>identity</code>), the <a href="https://www.twilio.com/docs/glossary/totp">TOTP channel</a>, and your app.
                Each Factor returns the secret seed and URI used to create a QR code.
            </p>
            <p>
                For this demo, we're asking for a username that will be displayed in the account name for the authenticator app.
            </p>
        </div>
        <a href="/">Reset</a>
    </main>
</body>
</html>

As you can see from the HTML above, it is a simplistic HTML page with a form, with a single field named "username". Note that the field's type and inputmode attributes are set to "text". This hints to browsers on mobile devices to render a virtual keyboard most appropriate for entering text input.

Then, back in src/Application.php, add the following code after the displayCreateTotpFactorForm() function.

public function processCreateTotpFactorForm(
    ServerRequestInterface $request,
    ResponseInterface $response,
): ResponseInterface {
    $postData = $request->getParsedBody();
    $username = $postData['username'] ?? '';
    $seed = substr(bin2hex(random_bytes(20)), 0, 32);
    $this->session->set('seed', $seed);

    $factor = $this->twilio
        ->verify
        ->v2
        ->services($this->verifyServiceSid)
        ->entities($seed)
        ->newFactors
        ->create($username, "totp");

    $this->session->set('friendly_name', $factor->friendlyName);
    $this->session->set('sid', $factor->sid);
    $this->session->set('otp_uri', $factor->binding['uri']);
    $this->session->set('url', $factor->url);

    $response = $response
        ->withHeader(
            'Location',
            $factor->status === 'unverified'
                ? $this->getNamedRoute("verify-user.display")->getPattern()
                : $this->getNamedRoute("create-totp.display")->getPattern(),
        )
        ->withStatus(StatusCodeInterface::STATUS_FOUND);
    return $response;
}

private function getNamedRoute(string $routeName): RouteInterface
{
    return $this->app->getRouteCollector()->getNamedRoute($routeName);
}

Then, add the following to the use statements at the top of the file:

use Fig\Http\Message\StatusCodeInterface;
use Slim\Views\Twig;

use function bin2hex;
use function random_bytes;
use function substr;

The processCreateTotpFactorForm() function creates a new TOTP Factor with Twilio Verify. The factor is seeded by a string created with random_bytes. This is then converted to hex format, of which the first 32 characters are retrieved, keeping it within the 8 - 64 character limit. As this is required later in the application, it's then stored in the current session.

Following this, it's used to create a new factor resource using the Twilio Rest Client. From the response to that request the following properties are stored in session for later use, the:

  • Friendly Name: The Factor's friendly name
  • SID: A 34 character string that uniquely identifies the Factor.
  • OTP URI: This stores the OTP configuration, including a shared secret and related parameters, for the OTP client (e.g., Authy) to use to generate the initial TOTP code.
  • URL:The URL of the Factor resource.

Then, if the new Factor's status is set to "unverified", the user is redirected to the verify-totp route. Otherwise, they're redirected back to the create-totp route to try again.

The getNamedRoute() function is a small utility function for retrieving a route object from the application based on its name. These objects contain details about one of the application's routes. From this object, the route's path is retrieved, which in turn simplifies the redirection process, when required.

Now, in src/Application.php, update the setupRoutes() function with the code below, to update the routing table as required:

public function setupRoutes(): void
{
    $this->app->get('/', [$this, 'displayCreateTotpFactorForm'])->setName("create-totp.display");
    $this->app->post('/', [$this, 'processCreateTotpFactorForm'])->setName("create-totp.process");
}

The code adds the GET and POST variants of the default route ("/") to the application's routing table; the GET version is handled by displayCreateTotpFactorForm(), and the POST version by processCreateTotpFactorForm().

Step 6: Add the ability to verify the TOTP Factor

You'll now add the functionality to render the form with the QR code for verifying the new Factor resource. Start by adding the code below to the end of src/Application.php.

public function displayVerifyUserForm(
    ServerRequestInterface $request,
    ResponseInterface $response,
): ResponseInterface {
    return Twig::fromRequest($request)
        ->render(
            $response,
            'verify-user.html.twig',
            [
                'qr_code' => (new QRCode())
                    ->render(
                        $this->session->get('otp_uri') ?? '',
                    ),
                'seed'    => $this->session->get('seed') ?? '',
            ],
        );
}

The showVerifyOtpForm() method renders templates/verify.html.twig, providing the form for the user to enter to validate their new TOTP Factor. The template will render two variables:

  • A QR code which embeds the unverified Factor's OTP URI
  • The unverified Factor's seed or identity

With that done, in the templates directory create a new file named verify-user.html.twig and paste the code below into the file.

<!DOCTYPE html>
<html>
<head>
    <title>Verify New TOTP Factor</title>
    <link href="https://assets.twilio.com/public_assets/paste-fonts/1.5.2/fonts.css" rel="stylesheet">
    <link href="/css/styles.css" rel="stylesheet">
</head>
<body class="container">
    <main>
        <h1>Verify New TOTP Factor</h1>
        <p class="mt-60 mb-60">
        This demo of the <a href="https://www.twilio.com/docs/verify/api">Twilio Verify API</a> shows how to set up two-factor authentication (2FA) with a third-party authenticator app like <a href="https://authy.com/download/">Authy</a> or Google Authenticator using the <a href="https://www.twilio.com/docs/glossary/totp">time-based one-time password (TOTP)</a> standard.
        </p>
        <hr>
        <form action="/challenge" method="post" class="mt-60">
            <p>Please scan the QR code in an authenticator app like Authy.</p>
            <div class="mt-20 mb-20" style="display: flex; flex: auto; column-gap: 0.25rem; flex-shrink: 0;">
                <img src="{{ qr_code }}" alt="QR Code" width="40%">
                <div class="mt-60">
                    <p>Or enter this code into your authentication app:</p>
                    <p><strong>{{ seed }}</strong></p>
                </div>
            </div>
            <label for="code">Enter the code generate by your authenticator app to verify this factor:</label>
            <div class="mt-20" style="display: flex; flex: auto; column-gap: 0.25rem; flex-shrink: 0;">
                <input
                    id="code"
                    inputmode="numeric"
                    name="code"
                    required
                    pattern="\d{6}"
                    placeholder="123456"
                    type="text"
                >
                <button type="submit" class="primary" style="flex-grow: 1;">Verify</button>
            </div>
        </form>
        <div style="background-color: #d6ebf0; padding: 2em; border-radius: 0.25rem;" class="mb-60">
            <h2 class="mb-60">Create a New Factor | What's happening here:</h2>
            <p style="line-height: 1.5;" class="mb-60">
                The API is <strong>creating a new TOTP <a href="https://www.twilio.com/docs/verify/api/factor#create-a-new-factor-resource">Factor</a></strong> when you click "Set up two-factor authentication".
                This is how the Verify API connects a user (<code>identity</code>), the <a href="https://www.twilio.com/docs/glossary/totp">TOTP channel</a>, and your app.
                Each Factor returns the secret seed and URI used to create a QR code.
            </p>
            <p>
                For this demo, we're asking for a username that will be displayed in the account name for the authenticator app.
            </p>
        </div>
        <a href="/">Reset</a>
    </main>
</body>
</html>

The HTML renders another, simplistic, form with the QR code to scan, and a field for the TOTP code generated by the user's authenticator app. The field uses the pattern attribute to ensure that the only valid input is a 6-digit code. It also sets the inputmode attribute to "numeric" to have mobile browsers display a keyboard appropriate for entering digits, making it easier for the user to only enter numeric input.

Next, back in src/Application.php, add the following function at the end of the class.

public function processVerifyUserForm(
    ServerRequestInterface $request,
    ResponseInterface $response,
): ResponseInterface {
    $postData = $request->getParsedBody();
    $factor = $this->twilio
        ->verify
        ->v2
        ->services($this->verifyServiceSid)
        ->entities($this->session->get('seed') ?? '')
        ->factors($this->session->get('sid') ?? '')
        ->update(
            [
                "authPayload" => $postData['code'] ?? '',
            ],
        );
    if ($factor->status === 'verified') {
        $this->setFlashMessage("Factor setup complete!");
    }

    $response = $response
        ->withHeader(
            'Location',
            $factor->status === 'verified'
                ? $this->getNamedRoute("qrcode.display")->getPattern()
                : $this->getNamedRoute("verify-user.display")->getPattern(),
        )
        ->withStatus(StatusCodeInterface::STATUS_FOUND);
    return $response;
}

The processVerifyUserForm() function retrieves the code that the user submitted from the request's POST data and attempts to verify the new Factor using it, along with the Factor's seed and SID, retrieved from the current session.

If the Factor is successfully verified, a confirmation message is flashed and the user is redirected to the route where they can enter QR codes generated by their application post-Factor creation, where the flashed message will be displayed, confirming that the Factor was successfully verified. Otherwise, they'll be redirected back to the verify TOTP Factor stage, to scan the QR code and try again.

With that done, add the following function in src/Application.php. It's a utility function to simplify setting flash messages.

private function setFlashMessage(string $message): void
{
    $flash = $this->app->getContainer()->get(Messages::class);
    assert($flash instanceof Messages);
    $flash->addMessage('message', $message);
}

Then, add the following to the use statements at the top of the file.

use Slim\Flash\Messages;
use chillerlan\QRCode\QRCode;

Now, add the next two routes to the application's routing table. Do that, similar to before, by updating setupRoutes() in src/Application.php to the following:

public function setupRoutes(): void
{
    $this->app->get('/', [$this, 'displayCreateTotpFactorForm'])->setName("create-totp.display");
    $this->app->post('/', [$this, 'processCreateTotpFactorForm'])->setName("create-totp.process");
    $this->app->get('/challenge', [$this, 'displayVerifyUserForm'])->setName("verify-user.display");
    $this->app->post('/challenge', [$this, 'processVerifyUserForm'])->setName("verify-user.process");
}

These add the GET and POST forms of the "/challenge" route, handled by the displayVerifyUserForm() and processVerifyUserForm() functions, respectively.

Step 7: Add the ability to validate TOTP codes after Factor verification

Now, you'll add the third and final feature: the ability to validate TOTP codes, post-Factor verification. Start by adding the following two functions to src/Application.php.

public function showQRCodeForm(
    ServerRequestInterface $request,
    ResponseInterface $response,
): ResponseInterface {
    $flash = $this->app->getContainer()->get(Messages::class);
    return Twig::fromRequest($request)
        ->render(
            $response,
            'enter-code.html.twig',
            [
                'friendlyName' => $this->session->get('friendly_name') ?? '',
                'message'      => $flash->getFirstMessage('message'),
                'seed'         => $this->session->get('seed') ?? '',
            ],
        );
}

public function processQRCodeForm(
    ServerRequestInterface $request,
    ResponseInterface $response,
): ResponseInterface {
    $postData = $request->getParsedBody();
    $challenge = $this->twilio
        ->verify
        ->v2
        ->services($this->verifyServiceSid)
        ->entities($this->session->get('seed') ?? '')
        ->challenges->create(
            $this->session->get('sid') ?? '',
            [
                "authPayload" => $postData['code'] ?? '',
            ],
        );

    $this->setFlashMessage(
        $challenge->status === "approved"
            ? "Verification success."
            : "Verification failed.",
    );

    $response = $response
        ->withHeader('Location', "/token")
        ->withStatus(StatusCodeInterface::STATUS_FOUND);
    return $response;
}

The first, showQRCodeForm(), renders an HTML form where the user can enter and submit a TOTP code generated by their authenticator app. The second, processQRCodeForm(), verifies the code with Twilio Verify.

If Twilio Verify marks the code as "approved", then a flash message confirming that is flashed. Otherwise, a message confirming that the code was invalid is flashed. The user is then redirected back to the TOTP code form, where the message will be displayed.

Now, in templates create a new file named enter-code.html.twig, and paste the code below into the file.

<!DOCTYPE html>
<html>
<head>
    <title>Enter TOTP Code</title>
    <link href="https://assets.twilio.com/public_assets/paste-fonts/1.5.2/fonts.css" rel="stylesheet">
    <link href="/css/styles.css" rel="stylesheet">
</head>
<body class="container">
    <main>
        <h1>Enter TOTP Code</h1>
        <p class="mt-60">
        This demo of the <a href="https://www.twilio.com/docs/verify/api">Twilio Verify API</a> shows how to set up two-factor authentication (2FA) with a third-party authenticator app like <a href="https://authy.com/download/">Authy</a> or Google Authenticator using the <a href="https://www.twilio.com/docs/glossary/totp">time-based one-time password (TOTP)</a> standard.
        </p>
        <hr class="mt-60">
        {% if message is not null %}
        {% set alert_type = message in ['Verification success.', 'Factor setup complete!'] ? 'success' : 'error' %}
        <p class="mt-60 alert alert-{{ alert_type }}">{{ message }}</p>
        {% endif %}
        <form action="/token" method="post" class="mt-60 mb-100">
            <label for="code">Enter the generated by your authenticator app:</label>
            <div class="mt-20" style="display: flex; flex: auto; column-gap: 0.25rem; flex-shrink: 0;">
                <input
                    id="code"
                    inputmode="numeric"
                    name="code"
                    required
                    pattern="\d{6}"
                    placeholder="123456"
                    type="text"
                >
                <button type="submit" class="primary" style="flex-grow: 1;">Verify</button>
            </div>
        </form>
        <p>
            Demo is running for username '{{ friendlyName }}' with identity '{{ identity }}'.
            <a href="">Validate a code</a> or <a href="/">Reset</a>
        </p>
    </main>
</body>
</html>

Similar to the previous template, this one renders a form with a field where the user can input and submit the code which their authenticator app generates. It also provides a link to start over and create a new Factor.

With the template created, make the third and final update to the application's routing table, by adding the following code to the end of the setupRoutes() function.

$this->app->get('/token', [$this, 'showQRCodeForm'])->setName("qrcode.display");
$this->app->post('/token', [$this, 'processQRCodeForm'])->setName("qrcode.process");

Step 8: Download the application's CSS file

The last step in the process is to download the application's CSS file from the project's GitHub repository, to the project's public/css directory, naming it styles.css.

Test that the application works

Finally, it's time to test that the code works as expected. Start the application by running the following command.

composer serve

Your server will start on port 8080, as shown by terminal output similar to the following.

2026/07/31 13:29:11 Server starting on :8080

You can now navigate to http://localhost:8080 to test the TOTP Factor creation process.

A web form page for setting up a new TOTP factor for two-factor authentication using Twilio Verify API.

Enter a username of your choice and click Set up two-factor authentication.

Verification page for setting up a new TOTP authentication factor with a QR code and field for code entry.

You will be redirected to the Verify New TOTP Factor form. With your authentication app, scan the QR code, enter the 6-digit code that it generates into the form, and click Verify.

Webpage interface prompting user to enter TOTP code for two-factor authentication with a Verify button.

You'll then be redirected to the Enter TOTP Code form, where you'll see whether the Factor was set up successfully or not, as in the screenshot above.

Webpage showing a field to enter TOTP code for 2FA verification with a Verification success message

If the Factor was set up successfully, enter the next 6-digit code into the Enter TOTP Code form and click Verify. Again, you should see if it was successfully verified or not, as in the screenshot above.

That's the essentials of implementing passwordless authentication in PHP using Twilio Verify

TOTP-based passwordless authentication using PHP and Twilio Verify presents a compelling alternative to traditional password-based systems.

It offers a blend of enhanced security and user convenience, making it an attractive option for modern applications. While passwordless auth introduces some extra complexity to your application, the benefits — especially regarding security and user experience — are worth the investment.

Matthew Setter is a PHP and Go Editor in the Twilio Voices team. He’s also the author of Mezzio Essentials and Deploy with Docker Compose. You can find him at msetter@twilio.com. He's also on LinkedIn and GitHub.

Otp icon created by Magnific on Flaticon.