FusionAuth QuickStart for PHP

On this page

This QuickStart explains how to add a login page and authentication to a website built with PHP. You'll begin with a simple PHP app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

Prerequisites#

This QuickStart requires:

If you use macOS or Windows, you need one of the following container management tools:

  • Docker Desktop
  • OrbStack (to use OrbStack for docker compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Create a Simple PHP App#

For this QuickStart, we'll use a single-file PHP app that reads and writes data to a text file:

  1. Create a folder for the app and navigate into it:

    $ mkdir php-quickstart && cd php-quickstart
    
  2. Create a file named index.php with the following code:

    <?php
    $noteFile = __DIR__ . '/note.txt';
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        file_put_contents($noteFile, $_POST['content'] ?? '');
        header('Location: /', true, 303);
        exit;
    }
    
    $note = is_file($noteFile) ? file_get_contents($noteFile) : '';
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40"><?= htmlspecialchars($note) ?></textarea><br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>

    When the form is submitted, the app saves the note to note.txt and redirects back to the page. Otherwise, it displays the note in a form.

  3. Run the app with PHP's built-in web server:

    $ php -S localhost:3000 index.php
    

    Passing index.php as the router script sends every request through it, so the server doesn't serve note.txt or other files in the folder directly.

  4. Open the app at http://localhost:3000.

  5. Type "Hello PHP" in the text area, then click Save Changes .

  6. In a file browser or terminal, look in the php-quickstart folder. You should see a new file named note.txt, with text content "Hello PHP".

  7. Press Ctrl+C on your keyboard to stop the server.

Install and Run FusionAuth#

Before we can add authentication to our PHP app, we need a local FusionAuth instance:

  1. Open your container management tool (listed in the prerequisites above).

  2. From the php-quickstart folder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:

    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    
  3. Navigate into the cloned directory:

    $ cd fusionauth-quickstart-app
    
  4. To start a local instance of FusionAuth, run the following command (omit the -d flag to see all Docker logs):

    $ docker compose up -d
    
  5. Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.

  6. Open http://localhost:9011/admin to access the FusionAuth Admin UI.

  7. Log in with these credentials:

    • Login: admin@example.com
    • Password: password
  8. Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our PHP app with FusionAuth.

  9. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our PHP app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.

Add FusionAuth to the PHP App#

Now that you have a working instance of FusionAuth and a working PHP app, let's use FusionAuth to add login to your PHP app:

  1. Navigate out of the fusionauth-quickstart-app folder, back to the php-quickstart folder that contains index.php and note.txt:

    $ cd ..
    
  2. Install the League OAuth 2.0 Client, which handles communication with our FusionAuth instance:

    $ composer require league/oauth2-client:2.10.0
    

    Composer creates a composer.json file and installs the library in the vendor folder.

  3. Create a file named config.php with the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):

    <?php
    return [
        'fusionAuthUrl' => 'http://localhost:9011',
        'clientId' => 'f0510a74-da7a-4101-a474-05e7f1d5ba7e',
        'clientSecret' => 'super-secret-secret-that-should-be-regenerated-for-production',
        'redirectUri' => 'http://localhost:3000/oauth-callback',
    ];
  4. Replace the contents of index.php with the following code:

    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    use League\OAuth2\Client\Provider\GenericProvider;
    
    $config = require __DIR__ . '/config.php';
    $provider = new GenericProvider([
        'clientId' => $config['clientId'],
        'clientSecret' => $config['clientSecret'],
        'redirectUri' => $config['redirectUri'],
        'urlAuthorize' => $config['fusionAuthUrl'] . '/oauth2/authorize',
        'urlAccessToken' => $config['fusionAuthUrl'] . '/oauth2/token',
        'urlResourceOwnerDetails' => $config['fusionAuthUrl'] . '/oauth2/userinfo',
        'scopes' => ['openid'],
        'pkceMethod' => GenericProvider::PKCE_METHOD_S256,
    ]);
    
    function redirect(string $url): never
    {
        header('Location: ' . $url, true, 303);
        exit;
    }
    
    session_start();
    $_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
    
    if ($isPost && !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        http_response_code(400);
        exit('Invalid CSRF token');
    }
    
    if ($path === '/login/start') {
        $authorizationUrl = $provider->getAuthorizationUrl();
        $_SESSION['oauth_state'] = $provider->getState();
        $_SESSION['oauth_pkce_code'] = $provider->getPkceCode();
        redirect($authorizationUrl);
    }
    
    if ($path === '/oauth-callback') {
        if (!isset($_GET['code'], $_GET['state'], $_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) {
            http_response_code(400);
            exit('Invalid login response');
        }
        $provider->setPkceCode($_SESSION['oauth_pkce_code']);
        $accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
        $user = $provider->getResourceOwner($accessToken)->toArray();
    
        session_regenerate_id(true);
        unset($_SESSION['oauth_state'], $_SESSION['oauth_pkce_code']);
        $_SESSION['user_id'] = $user['sub'];
        redirect('/');
    }
    
    if ($path === '/logout' && $isPost) {
        session_destroy();
        redirect($config['fusionAuthUrl'] . '/oauth2/logout?' . http_build_query(['client_id' => $config['clientId']]));
    }
    
    if ($path === '/login') { ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a href="/login/start">Log in with FusionAuth</a>
    </body>
    </html>
    <?php
        exit;
    }
    
    if (!isset($_SESSION['user_id'])) {
        redirect('/login');
    }
    
    $noteFile = __DIR__ . '/note.txt';
    
    if ($isPost) {
        file_put_contents($noteFile, $_POST['content'] ?? '');
        redirect('/');
    }
    
    $note = is_file($noteFile) ? file_get_contents($noteFile) : '';
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40"><?= htmlspecialchars($note) ?></textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>

    The new code connects the app to FusionAuth:

    • GenericProvider tells the League OAuth 2.0 Client how to talk to FusionAuth. It uses the client Id, client secret, the FusionAuth authorize, token, and UserInfo endpoints, and PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges..
    • session_start starts a native PHP session, which keeps the user logged in to the app with a cookie. The session also stores a random CSRF token. Both forms include the token in a hidden field, and the app rejects any POST request without a matching token, to prevent CSRFAn attack in which a malicious site makes the user's browser send an unwanted request to a site where the user is logged in. The OAuth 2.0 state parameter protects the authorization flow from CSRF..
    • The /login route shows a page with a Log in with FusionAuth link to /login/start, which sends the user to the FusionAuth login page. Before it redirects, the app stores the state value and PKCE code verifier in the session.
    • The /oauth-callback route receives the authorization code from FusionAuth. It checks that state matches the session, exchanges the code and code verifier for an access token, and uses the access token to request the user's details from FusionAuth's UserInfo endpoint. The app then stores the user's Id (the sub claim) in the session.
    • The /logout route destroys the PHP session, then sends the user to FusionAuth's /oauth2/logout endpoint so the FusionAuth session ends too. FusionAuth then sends the user to the app's login page.
    • Any other request without a logged-in user redirects to /login.
  5. Run the app, which now uses FusionAuth login:

    $ php -S localhost:3000 index.php
    
  6. Open the app at http://localhost:3000 and click Log in with FusionAuth .

  7. Log in with the following credentials:

    • Login: richard@example.com
    • Password: password
  8. Edit and save the note in the authenticated PHP app.

  9. Click Logout . FusionAuth ends your session and sends you back to the login page.

  10. Press Ctrl+C on your keyboard to stop the server.

Add Independent Notes for Each User#

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

  1. Open the FusionAuth Admin UI at http://localhost:9011/admin.

  2. Log in with the following credentials:

    • Login: admin@example.com
    • Password: password
  3. Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.

    • Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
    • In the Registration field list, turn on the Enabled and Required switches for the following rows:
      • Birthdate
      • First name
      • Last name
  4. Click Save in the top right of the page to save your changes to self-service registration.

  5. Navigate to Users . In the Richard Hendricks row, click Select -> Manage .

  6. In the Source tab, look for the firstName and lastName fields. That's what we'll use to personalize the UI for each user. We'll use the user's id field to generate a unique name for each user's note.

  7. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our PHP app.

  8. Replace the contents of index.php with the following code:

    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    use League\OAuth2\Client\Provider\GenericProvider;
    
    $config = require __DIR__ . '/config.php';
    $provider = new GenericProvider([
        'clientId' => $config['clientId'],
        'clientSecret' => $config['clientSecret'],
        'redirectUri' => $config['redirectUri'],
        'urlAuthorize' => $config['fusionAuthUrl'] . '/oauth2/authorize',
        'urlAccessToken' => $config['fusionAuthUrl'] . '/oauth2/token',
        'urlResourceOwnerDetails' => $config['fusionAuthUrl'] . '/oauth2/userinfo',
        'scopes' => ['openid', 'profile'],
        'scopeSeparator' => ' ',
        'pkceMethod' => GenericProvider::PKCE_METHOD_S256,
    ]);
    
    function redirect(string $url): never
    {
        header('Location: ' . $url, true, 303);
        exit;
    }
    
    session_start();
    $_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
    
    if ($isPost && !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        http_response_code(400);
        exit('Invalid CSRF token');
    }
    
    if ($path === '/login/start') {
        $authorizationUrl = $provider->getAuthorizationUrl();
        $_SESSION['oauth_state'] = $provider->getState();
        $_SESSION['oauth_pkce_code'] = $provider->getPkceCode();
        redirect($authorizationUrl);
    }
    
    if ($path === '/oauth-callback') {
        if (!isset($_GET['code'], $_GET['state'], $_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) {
            http_response_code(400);
            exit('Invalid login response');
        }
        $provider->setPkceCode($_SESSION['oauth_pkce_code']);
        $accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
        $user = $provider->getResourceOwner($accessToken)->toArray();
    
        session_regenerate_id(true);
        unset($_SESSION['oauth_state'], $_SESSION['oauth_pkce_code']);
        $_SESSION['user_id'] = $user['sub'];
        $_SESSION['user_name'] = trim(($user['given_name'] ?? '') . ' ' . ($user['family_name'] ?? '')) ?: 'writer';
        redirect('/');
    }
    
    if ($path === '/logout' && $isPost) {
        session_destroy();
        redirect($config['fusionAuthUrl'] . '/oauth2/logout?' . http_build_query(['client_id' => $config['clientId']]));
    }
    
    if ($path === '/login') { ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a href="/login/start">Log in with FusionAuth</a>
    </body>
    </html>
    <?php
        exit;
    }
    
    if (!isset($_SESSION['user_id'])) {
        redirect('/login');
    }
    
    $name = $_SESSION['user_name'];
    $noteFile = __DIR__ . '/user_data/note-' . $_SESSION['user_id'] . '.txt';
    
    if ($isPost) {
        if (!is_dir(__DIR__ . '/user_data')) {
            mkdir(__DIR__ . '/user_data');
        }
        file_put_contents($noteFile, $_POST['content'] ?? '');
        redirect('/');
    }
    
    $note = is_file($noteFile) ? file_get_contents($noteFile) : "Write a note, $name.";
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Welcome, <?= htmlspecialchars($name) ?></h1>
        <form method="post" action="/">
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40"><?= htmlspecialchars($note) ?></textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>

    The new code adds the profile scope, so the UserInfo response includes the user's first and last name (given_name and family_name). The callback stores the name in the session next to the user's Id. The notes page greets the user by name and stores each user's note in a separate file in the user_data folder, named after the user's Id.

  9. Run the app:

    $ php -S localhost:3000 index.php
    
  10. Open the app at http://localhost:3000 and click Log in with FusionAuth .

  11. Log in with the following credentials:

    • Login: richard@example.com
    • Password: password
  12. In a separate private or incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth .

  13. Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.

  14. Edit and save your own note. Your name appears at the top of the page and in the default note text.

Your PHP app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a note-<id>.txt file in the user_data directory. To identify which note belongs to which user, compare the id in the file name with the id field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.

Summary#

In this QuickStart, FusionAuth handled login for your PHP app:

  • The League OAuth 2.0 Client sent users to the FusionAuth login page and exchanged the authorization code for an access token, so the app never saw their passwords.
  • The session check in index.php sent logged-out users to the login page instead of the notes page.
  • FusionAuth's UserInfo endpoint gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
  • FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

Next Steps#

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.

FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.